【问题标题】:How to update UITableViewCell?如何更新 UITableViewCell?
【发布时间】:2023-04-03 10:18:01
【问题描述】:

我有自定义 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 没有更新。我做错了什么?

【问题讨论】:

    标签: ios swift uitableview


    【解决方案1】:

    这个

    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)
    

    【讨论】:

      【解决方案2】:
      • 在控制器中创建属性count

        var count = 0 // or another default value
        
      • cellForRow 中,将count 的值赋给单元格的count 属性

        if indexPath.row == 2 {
           cell.count = count
        }
        
      • onDidReceiveEvent 更新count 并重新加载行

        @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)
        }
        

      【讨论】:

        【解决方案3】:

        如果不知道您的代码是什么样子就很难说,但我假设您的 UITableViewDataSource 不是最新的,因为 onDidReceiveEvent() 被调用。

        因此,如果我的假设是正确的,那么您唯一需要做的就是确保在致电 reloadRows() 之前更新您的 UITableViewDataSource

        @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)
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-06-05
          • 1970-01-01
          • 2016-07-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-10-31
          • 2019-08-30
          相关资源
          最近更新 更多