我正在尝试检测 UICollectionViewCell
中的 UITableViewCell
中的按钮点击。
UICollectionView
的委托(delegate)和数据源是我的 ViewController
。每个 UICollectionViewCell
中有一个 UITableView
。 UITableViewCell
的委托(delegate)和数据源是 UICollectionViewCell
。
我需要检测 ViewController
中的按钮点击。
View Controller
@IBOutlet collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
}
UICollectionView
@IBOutlet tableView: UITableView!
override func awakeFromNib() {
super.awakeFromNib()
tableView.delegate = self
tableView.dataSource = self
}
UITableViewCell
@IBAction func buttonTapped(_ sender: CustomButton) {
// Detect Button Tap in ViewController
}
最佳答案
我建议您使用委托(delegate)模式。
因此,您需要一种用于 TableView 单元格的协议(protocol)和一种用于 Collection View 单元格的协议(protocol)
protocol TableCellDelegate: class {
func buttonPressed(_ sender: CustomButton)
}
protocol CollectionCellDelegate: class {
func buttonInTableCellPressed(_ sender: CustomButton)
}
现在创建delegate
细胞子类的变量
class TableCell: ... {
weak var delegate: TableCellDelegate?
}
class CollectionCell: ... {
weak var delegate: CollectionCellDelegate?
}
继续实现TableCellDelegate
至CollectionView
并在表格单元格委托(delegate)方法内调用单元格委托(delegate)的方法
extension CollectionCell: TableCellDelegate {
func buttonPressed(_ sender: CustomButton) {
delegate?.buttonInTableCellPressed(sender)
}
}
下一步实现CollectionCellDelegate
到你的 View Controller
extension ViewController: CollectionCellDelegate {
func buttonInTableCellPressed(_ sender: CustomButton) {
... // this is called when button in table view cell is pressed
}
}
现在,不要忘记在 cellForItemAt
内设置集合单元格的委托(delegate)在ViewController
和 cellForRowAt
内的表格单元格的委托(delegate)在CollectionCell
class ViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
...
cell.delegate = self
...
}
}
class CollectionCell: UICollectionViewCell, UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
...
cell.delegate = self
...
}
}
现在,最后,按下按钮时调用表格单元格内委托(delegate)的方法
@IBAction func buttonTapped(_ sender: CustomButton) {
delegate?.buttonPressed(sender)
}
关于ios - 如何检测 UICollectionViewCell 中 UITableViewCell 中的按钮点击?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54177665/