gpt4 book ai didi

ios - UICollectionViewCell 与它的 UICollectionViewController 对话

转载 作者:行者123 更新时间:2023-12-01 16:14:18 26 4
gpt4 key购买 nike

尽管可能是主观的,但我想知道如何进行自定义 UICollectionViewCell那当它的UIButton按下,通知自定义 UICollectionViewController做什么。

我的第一个想法是使用 delegateCustomCell如下:

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)在哪里定义为:
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 之间进行通信?及其父 Controller ?

感谢您的任何建议。

最佳答案

是的,这肯定是正确的解决方案。 您的自定义单元是盲目的,它们对您的 Controller 一无所知。他们只触发委托(delegate)方法。

但是,还有另一种正确的解决方案,那就是观察。 有人喜欢委托(delegate),有人喜欢观察。您可以使用 NotificationCenter发布有关在您的单元格中发生的触摸的通知,并使您的 Controller 成为对这些通知作出 react 的观察者。

// inside your cell
NotificationCenter.default.post(name: Notification.Name("ButtonPressed"), object: nil)

// inside your controller
NotificationCenter.default.addObserver(self, selector: #selector(someHandler), name: Notification.Name("ButtonPressed"), object: nil)

还有你的功能 someHandler()当您的 Controller (观察者)捕获已发布的事件时,将处理该调用。

还有 KVO ,但它很困惑,不适合那种特殊情况,因为你有多个单元格。

设置通信 channel 的另一种方法是 绑定(bind) .它可以是手动编写的,也可以是响应式的(例如,使用 ReactiveSwift)。

例如手动一:
// in your controller 
cell.pressHandler = {
// do something
...
}

// in your cell
var pressHandler: (() -> Void)?

...

// when the button is pressed you execute that handler
pressHandler?()

关于ios - UICollectionViewCell 与它的 UICollectionViewController 对话,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50039663/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com