我在多个tableview
中使用UITableViewCell的自定义单元格,并且它工作正常,但我想知道,自定义单元格用于哪个tableview?
例如
假设ViewControllerA
的自定义单元格为tableView
,即(ReuseIdentifier)cellA
。
此外ViewControllerB
还有tableView
个自定义单元格,即(ReuseIdentifier)cellB
但两个单元都有相同的类。
现在,从ViewController
开始,任何按钮操作都会推动该类。
现在,该自定义单元格将如何理解使用哪个tableView
?
有什么办法吗?
任何答案都将不胜感激
由于
答案 0 :(得分:0)
您可以为tableView(_ tableView: UITableView, cellForRowAt indexPath: UIIndexPath)
中的每个单元格实现委托。同样可以在ViewController
中完成,它将从您分配了ViewController
到delegate
属性的所有单元格接收回调。
请参阅下面的示例,并原谅我的拼写错误,没有IDE。
<强> YourCell.swift 强>
protocol YourCellDelegate {
func cellDidTapButton(_ cell: YourCell)
}
class YourCell {
var delegate: YourCellDelegate?
...
// Action linked to your cells button
@IBAction func didTapButton(_ sender: Any) {
delegate?.cellDidTapButton(_ cell: YourCell)
}
}
<强> ViewControllerA.swift 强>
class ViewControllerA: UITableViewDataSource {
var tableView: UITableView!
...
func tableView(_ tableView: UITableView, cellForRowAt indexPath: UIIndexPath) {
if let cell = tableView.dequeueReusableCell(withIdentifier:"ReuseIdentifier", at: indexPath) as? YouCell {
// Do cell configuration
...
cell.delegate = self
}
}
}
extension UIViewControllerB: YourCellDelegate {
func cellDidTapButton(_ cell: YourCell) {
// Get indexPath of this cell
if let indexPath = self.tableView.indexPathForRow(at:cell.center) {
// Do action specific to this cell
}
}
}