一个`UITableViewCell`类用于多个`UITableView`

时间:2017-07-20 15:23:49

标签: ios uitableview

我在多个tableview中使用UITableViewCell的自定义单元格,并且它工作正常,但我想知道,自定义单元格用于哪个tableview?

例如

假设ViewControllerA的自定义单元格为tableView,即(ReuseIdentifier)cellA。 此外ViewControllerB还有tableView个自定义单元格,即(ReuseIdentifier)cellB

但两个单元都有相同的类。

现在,从ViewController开始,任何按钮操作都会推动该类。

现在,该自定义单元格将如何理解使用哪个tableView

有什么办法吗?

任何答案都将不胜感激

由于

1 个答案:

答案 0 :(得分:0)

您可以为tableView(_ tableView: UITableView, cellForRowAt indexPath: UIIndexPath)中的每个单元格实现委托。同样可以在ViewController中完成,它将从您分配了ViewControllerdelegate属性的所有单元格接收回调。

请参阅下面的示例,并原谅我的拼写错误,没有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
        }
    }
}