我有自定义 UITableViewCell 属性 count: Int?
。根据这个属性,我渲染了 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)
关于ios - 如何更新 UITableViewCell?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59471241/