![](/img/trans.png)
[英]Passing data from view controller to table view controller in ios swift 2
[英]Passing message from View Controller to a class in Swift
通过使用委托,我试图将数据从视图控制器传递到TableView类,该类将显示正确数量的单元格。 首先,我需要将数组传递给该类(此处使用String代替进行调试)
在我的ViewController中:
protocol GroupBillVCDelegate{
func passFriendArray(string: String)
}
...
class GroupBillViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{
var delegate:GroupBillVCDelegate? // for delegate passing message
...
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if (tableView == self.FriendTableView){
let friendListCell = tableView.dequeueReusableCell(withIdentifier: "friendListCell") as! CategoryRow
// transfer friends array to CategoryRow
self.delegate?.passFriendArray(string: "Hello There")
return friendListCell
}
}
}
在TableViewCell类中:
class CategoryRow: UITableViewCell, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, GroupBillVCDelegate {
var s:String = String()
func passFriendArray(string: String) {
s = string
print(string)
}
...
// used for horizontal scrolling
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
passFriendArray(string: s) // message supposed to appear here
print ("TEST")
return 10
}
...
}
我在设置代表时遇到麻烦。 当我运行时,控制台不会显示该消息。 为什么不通过?
可以将代表视为办公桌上的对讲机,该对讲机可以连接到助手室。
这行:
var delegate:GroupBillVCDelegate? // for delegate passing message
定义对讲机,但不连接任何东西。 如果您按下对讲机上的按钮,则它不会连接任何东西。
代码self.delegate?.passFriendArray(string: "Hello There")
如果有委托,则使用“可选链接”将消息发送给委托,如果没有委托,则使用丢弃消息。
您缺少的是为委托分配一些东西:
self.delegate = someObjectThatConformsToGroupBillVCDelegateProtocol
委托是一对一的关系。
话虽这么说,让表视图单元格成为视图控制器的委托真的没有任何意义。 表格视图有多个单元格。 视图控制器的委托应该是哪个单元格? 为什么那个细胞而不是另一个?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.