我有具有属性count: Int?的自定义UITableViewCell。根据此属性,我渲染了一定数量的UITextFields。 (例如count == 1->一个UITextField,count == 2->两个UITextField)。

稍后,当某些事件发生时,我想为此标签设置新的值。这是我的工作:

在我的UIViewController中:

@objc func onDidReceiveEvent(_ notification: Notification) {
        guard let count = notification.object as? Int else { return }
        guard let cell = self.tableView.cellForRow(at: IndexPath(row: 2, section: 0)) as? MyCustomCell else { return }

        cell.count = count
        self.tableView.reloadRows(at: [IndexPath(row: 2, section: 0)], with: .automatic)
        // I also tried self.tableView.reloadData()
}


我将断点放在override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?)内,并且看到在此代码块之后单元正在更新,但是属性count没有更新。我究竟做错了什么?

最佳答案

这个

override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?)


在创建单元格时调用一次,然后将单元出队,您需要添加一个

func configure(_ count:Int)


在单元格自定义类中,然后从cellForRowAt调用它,或在此处刷新

guard let cell = self.tableView.cellForRow(at: IndexPath(row: 2, section: 0)) as? MyCustomCell else { return }
cell.configure(count)

07-24 09:51
查看更多