ios - 如何更新 UITableViewCell?

标签 ios swift uitableview

我有自定义 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/

相关文章:

ios - UITextView 滚动不起作用

iOS 扫描二维码成功后如何关闭相机 Swift 4

swift - 使用 UIBezierPath 的带有圆角的 TableView 页眉和页脚

iphone - UITableView tableFooterView 奇怪的调整大小

ios - 如何使用 Storyboard 进行水平掩膜缝合?

ios - 如何使用 AFnetworking 发送 post 请求?

Swift:带有圆顶边缘和彩色边框的 UIVisualEffectView

ios - 在 map View 上获取注释框

ios - 重用 UITableViewCell 时缺少 subview

ios - 将侧边菜单中的数据传回其原始 View Controller