正如 NSAdi 所说,您走在正确的轨道上,但是对于单个任务(例如通知按钮按下情况)来说,委托模式的开销有点大。
我更喜欢使用闭包,因为它们是轻量级的并且有助于将相关代码保持在一起。
使用闭包
这就是我一直在做的事情UITableView
。所以这将适用于UICollectionView
too.
class MyTableViewCell: UITableViewCell {
var myButtonTapAction: ((MyTableViewCell) -> Void)?
@IBAction func myButtonTapped(_ sender: Any) {
myButtonTapAction?(self)
}
}
所以当我将我的单元出队并将其投射到MyTableViewCell
我可以设置一个自定义操作,如下所示:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "myCellReuseIdentifier", for: indexPath) as! MyTableViewCell
cell.myButtonTapAction = { cell in
// Put your button action here
// With cell you have a strong reference to your cell, in case you need it
}
}
使用直接引用
当你出队时UICollectionView
您可以通过将单元格转换为单元格的自定义子类来获取对按钮的引用。
然后只需执行以下操作
cell.button.addTarget(self, action: #selector(didTapButton(_:)), forControlEvents: .TouchUpInside)
而外面有一个函数:
@objc func didTapButton(_ sender: UIButton) {
// Handle button tap
}
这样做的缺点是您无法直接访问您的手机。你可以使用button.superview?
但这不是一个好主意,因为您的视图层次结构可能会改变......