Ios 如何更新UITableViewCell?
我有一个自定义UITableViewCell,其属性计数为:Int?。根据此属性,我渲染UITextFields的数量。例如,计数==1->一个UITextField,计数==2->两个UITextFields 稍后当一些事件发生时,我想为这个标签设置新的值。以下是我的工作: 在我的UIViewController中:Ios 如何更新UITableViewCell?,ios,swift,uitableview,Ios,Swift,Uitableview,我有一个自定义UITableViewCell,其属性计数为:Int?。根据此属性,我渲染UITextFields的数量。例如,计数==1->一个UITextField,计数==2->两个UITextFields 稍后当一些事件发生时,我想为这个标签设置新的值。以下是我的工作: 在我的UIViewController中: @objc func onDidReceiveEvent(_ notification: Notification) { guard let count = no
@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 initstyle的内部:UITableViewCell.CellStyle,reuseIdentifier:String?我看到在这段代码之后,单元格正在更新,但是属性计数没有更新。我做错了什么?这个
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?)
在创建单元时调用一次,然后该单元退出队列。您需要添加
func configure(_ count:Int)
在您的cell自定义类中,并从cellForRowAt调用它,或在此处刷新
guard let cell = self.tableView.cellForRow(at: IndexPath(row: 2, section: 0)) as? MyCustomCell else { return }
cell.configure(count)
在控制器中,创建属性计数
在cellForRow中,将count的值指定给单元格的count属性
if indexPath.row == 2 {
cell.count = count
}
在onDidReceiveEvent中更新计数并重新加载行
@objc func onDidReceiveEvent(_ notification: Notification) {
guard let count = notification.object as? Int else { return }
self.count = count
self.tableView.reloadRows(at: [IndexPath(row: 2, section: 0)], with: .automatic)
}
在不知道代码外观的情况下很难判断,但我假设在调用onDidReceiveEvent时,UITableViewDataSource不是最新的 因此,如果我的假设是正确的,那么您需要做的唯一一件事就是确保在调用reloadRows之前更新UITableViewDataSource:
@objc func onDidReceiveEvent(_ notification: Notification) {
guard let count = notification.object as? Int else { return }
self.count = count
self.tableView.reloadRows(at: [IndexPath(row: 2, section: 0)], with: .automatic)
}
@objc func onDidReceiveEvent(_ notification: Notification) {
guard let count = notification.object as? Int else { return }
// Make sure that the dataSource of self.tableView is updated before you update the cell
self.tableView.reloadRows(at: [IndexPath(row: 2, section: 0)], with: .automatic)
}