【发布时间】:2018-04-26 09:37:36
【问题描述】:
尽管可能是主观的,但我想知道如何使用自定义UICollectionViewCell,当按下它的UIButton 时,会通知自定义UICollectionViewController 要做什么。
我的第一个想法是在CustomCell 中使用delegate,如下所示:
class CustomCell: UICollectionViewCell {
var delegate: CustomCellDelegate?
static let reuseIdentifier = "CustomCell"
@IBOutlet weak private var button: UIButton! {
didSet {
button.addTarget(self, action: #selector(self.toggleButton), for: .touchUpInside)
}
}
@objc private func toggleButton() {
delegate?.didToggleButton()
}
}
CustomCellDelegate 的类协议定义为:
protocol CustomCellDelegate: class {
func didToggleButton()
}
UICollectionViewController 然后实现didToggleButton 函数并将自己作为delegate 分配给每个单元格,如下所示:
class CustomCollectionViewController: UICollectionViewController, CustomCellDelegate {
func didToggleButton() {
// do some stuff and then update the cells accordingly ...
collectionView?.reloadData()
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let customCell = collectionView.dequeueReusableCell(withReuseIdentifier: CustomCell.reuseIdentifier, for: indexPath) as? CustomCell else { fatalError("Unexpected indexPath") }
customCell.delegate = self
return customCell
}
}
这是解决此问题的正确方法,还是有其他方法可以在 UICollectionViewCell 与其父控制器之间进行通信?
感谢您的任何建议。
【问题讨论】:
-
也许是这样。委派是一种正统的方法,可以很好地实现效果。你也可以使用binding。
-
@Nitish 感谢您的 cmets ...
标签: ios swift uicollectionview delegates uicollectionviewcell