【问题标题】:UITableViewCell's attributed text not updatingUITableViewCell 的属性文本未更新
【发布时间】:2018-07-27 13:49:47
【问题描述】:

我有一个通过 Core Data 的NSFetchedResultsControler 连接的表视图。这些单元格有一个带有属性文本的UILabel 和一个代表对象的isEnabled 值的UISwitch。在单元格内,我有一个功能:

func configure(with viewModel: CellViewModel) {
    myCustomLabel.attributedText = viewModel.attributedText // NSMutableAttributedText
}

切换开关会更改对象上的isEnabled 值,从而引发NSFetchedResultsControler,它调用:

let cell: MyTableViewCell = tableView.dequeueReusableCell(forIndexPath: indexPath) //my custom helper method
let cellViewModel = viewModel.itemModel(at: indexPath)
cell.configure(with: cellViewModel)

我不想使用reloadDatareloadRowsreloadSections,因为我想在更改单元格状态的同时保留动画,并在仅翻转开关时避免单元格褪色动画。我知道这是一种非常糟糕的方法,但它需要保留动画。

问题是:标签上的attributedText 不会立即更改。只有在重用单元格后。调试器正确显示标签的新值。我试过了:

  • this suggestion(预先设置字体和颜色为nil),
  • 在标签和超级视图上调用 setNeedDisplay
  • 先设置无归属文本,再设置attributedText

没有任何作用。你知道为什么会这样吗?

系统为 iOS 11.4,XCode 9.4.1。

【问题讨论】:

    标签: swift uitableview core-data


    【解决方案1】:

    如果您将 myCustomLabel.attributedText = viewModel.attributedText 包装在 DispatchQueue.main.async { } 中,它将起作用:

    DispatchQueue.main.async { myCustomLabel.attributedText = viewModel.attributedText }

    【讨论】:

      【解决方案2】:

      我认为不是:

      let cell: MyTableViewCell = tableView.dequeueReusableCell(forIndexPath: indexPath)
      

      你应该使用:

      tableView.cellForRow(at: indexPath)
      

      这将为您返回该 indexPath 的单元格实例。通过调用“dequeueReusableCell”,你实际上是在说你想要一个新的 Cell。

      假设我得到了你想要达到的目标,而你的 sn-p 不是来自

      func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
      

      方法。

      如果这不起作用,可能值得添加一个 git 链接来查看您的代码。

      希望有帮助!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-11-11
        • 2017-06-05
        • 1970-01-01
        • 1970-01-01
        • 2019-09-28
        • 2013-03-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多