[英]Passing message from View Controller to a class in Swift
By using delegates, I'm trying to pass data from a view controller to a TableView class that will display the correct number of cells. 通过使用委托,我试图将数据从视图控制器传递到TableView类,该类将显示正确数量的单元格。 First, I needed to pass the array to that class (using a String here instead for debugging) 首先,我需要将数组传递给该类(此处使用String代替进行调试)
Inside my ViewController: 在我的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
}
}
}
Inside the TableViewCell class: 在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
}
...
}
I have trouble setting up the delegate. 我在设置代表时遇到麻烦。 When I run, the console does not display the message. 当我运行时,控制台不会显示该消息。 Why is it not being passed? 为什么不通过?
Think of a delegate as an intercom on your desk that can be connected to your assistant's office. 可以将代表视为办公桌上的对讲机,该对讲机可以连接到助手室。
This line: 这行:
var delegate:GroupBillVCDelegate? // for delegate passing message
Defines the intercom, but doesn't connect it to anything. 定义对讲机,但不连接任何东西。 If you press the button on the intercom, it doesn't connect to anything. 如果您按下对讲机上的按钮,则它不会连接任何东西。
The code self.delegate?.passFriendArray(string: "Hello There")
代码self.delegate?.passFriendArray(string: "Hello There")
uses "optional chaining" to send a message to the delegate if there is one, and drop the message if there is no delegate. 如果有委托,则使用“可选链接”将消息发送给委托,如果没有委托,则使用丢弃消息。
The thing you're missing is assigning something to the delegate: 您缺少的是为委托分配一些东西:
self.delegate = someObjectThatConformsToGroupBillVCDelegateProtocol
A delegate is a one-to-one relationship. 委托是一对一的关系。
All that being said, it doesn't really make sense to make a table view cell the delegate of a view controller. 话虽这么说,让表视图单元格成为视图控制器的委托真的没有任何意义。 The table view has more than one cell. 表格视图有多个单元格。 Which cell should be the view controller's delegate? 视图控制器的委托应该是哪个单元格? Why that cell and not another one? 为什么那个细胞而不是另一个?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.