首页 > 解决方案 > 单击 UITableViewCell 时更新标签

问题描述

我有一个包含许多表格视图单元格的表格视图。当用户单击单元格时,我想更新单元格的标签文本。

这是我的表视图控制器类:

class MyTableViewController: UITableViewController {
    var data = [Data]()

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self

        // Here I fetch and populate the data list
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellIdentifier = "MyTableViewCell"

        guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? MyTableViewCell else {
            fatalError("The dequeued cell is not an instance of MyTableViewCell.")
        }

        let cellData = data[indexPath.row]

        cell.initialize(data: cellData)

        return cell
    }
}

这是我的表格视图单元格类:

class MyTableViewCell: UITableViewCell {
    var data: Data?

    @IBOutlet weak var nameLabel: UILabel!

    func initialize(data: Data) {
        self.data = data

        if let cellName = data.name {
            nameLabel.text = cellName
        }
    }
}

nameLabel当用户单击表格视图单元格时,如何更改上述文本(为“已单击”)?

标签: iosswiftuitableview

解决方案


毫无疑问,您可以通过不同的方式来处理这个问题,但这是我的建议:

实现 UITableViewDelegate 方法tableView(_:didSelectRowAt:)tableView(_:didDeselectRowAt:). 为表格视图中的单元格的数据模型添加一个selected布尔值,并在选择/取消选择单元格时更新该布尔值的状态。

然后修改您的cellForRow(at:)方法,使其使用selected标志来决定在标签中显示什么。

最后,让您的tableView(_:didSelectRowAt:)andtableView(_:didDeselectRowAt:)方法告诉表格视图重新加载新选择/取消选择的单元格。


推荐阅读