1

I have a table view that is connected through a Core Data's NSFetchedResultsControler. The cells have a UILabel with attributed text and a UISwitch representing the object's isEnabled value. Inside the cell, I have a function:

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

Chaning the switch changes the isEnabled value on the object, which in cause raises the NSFetchedResultsControler, which calls:

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

I do not want to use reloadData, reloadRows or reloadSections, because I want to keep animations while changing the cell's state and avoid cell fading animation if only switch is flipped. I know this is quite bad approach but it's required to keep the animations.

The problem is: The attributedText doesn't change on the label immediately. Only after cell is reused. The debugger displays the new value of the label correctly. I have tried:

  • this suggestion (setting font and color to nil beforehand),
  • calling setNeedDisplay on both the label and it's superview
  • setting the non-attributed text first, then attributedText

Nothing works. Do you have any ideas why it's like that?

System is iOS 11.4, XCode 9.4.1.

Kacper Cz
  • 504
  • 3
  • 17

2 Answers2

1

If you wrap myCustomLabel.attributedText = viewModel.attributedText in a DispatchQueue.main.async { } it will work:

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

Armand
  • 11
  • 4
0

I think that instead of:

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

You should use:

tableView.cellForRow(at: indexPath)

That will return you the cell instance for that indexPath. By calling "dequeueReusableCell" you are essentially saying you want a new Cell.

That assumes that I get what you are trying to achieve and your snippet is not from the

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

method.

If that doesn't work might be worth adding a git link to take a look at your code.

Hope that helps!