我想使用委托(delegate)让我的单元格(来自 UICollectionView)与我的 ViewController 通信。
在我的 Cell.swift 文件中,我像这样声明所需的协议(protocol)(在 Cell 类之外):
protocol CellDelegate: class {
func someMethod(param1: String?, param2 param2: Bool)
}
在同一个文件中,我声明委托(delegate)如下:
class Cell: UICollectionViewCell {
weak var delegate: CellDelegate?
// ... some code ...
@IBAction func someAction(sender: AnyObject) {
delegate?.someMethod(param1, param2: true)
}
}
现在在我的 ViewController 中,我正在实现 someMethod
:
extension ViewController: CellDelegate {
func someMethod(param1: String?, param2 param2: Bool) {
// ... some code ...
}
}
问题:我无法将协议(protocol)与其实现链接起来,协议(protocol)中的 cmd + click
无处可寻。在我的 @IBAction
中,someMethod
没有崩溃,但它什么也没做。
我看到了this topic关于这个主题,但我不知道在哪里实现第 6 步。
你能帮帮我吗?
感谢您的宝贵时间。
最佳答案
您错过了最后一步:填充 Cell
类的 delegate
属性。我通常在 cellForRowAtIndexPath
中这样做:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.table.dequeueReusableCellWithIdentifier("myCellId") as! Cell
cell.delegate = self
...
return cell
}
请注意,使用委托(delegate)时没有魔法或自动行为:
- 委托(delegate)是一个协议(protocol)(您的
CellDelegate
协议(protocol)) - 您在要响应委托(delegate)调用的类中实现协议(protocol)(您在
ViewController
类中实现) - 您在调用委托(delegate)方法的类中创建委托(delegate)属性(您在
Cell
类中创建) - 您使用类的实际实例初始化委托(delegate)属性
您只是错过了最后一步,留下了未初始化的属性,因此任何使用可选链接的调用都将计算为 nil
(就像您在 someAction
方法中所做的那样),并且没有任何结果发生了。
关于ios - Swift - 委托(delegate) - 如何将协议(protocol)链接到已实现的委托(delegate)方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30872087/