Move Rows | raywenderlich.com


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/10796666-table-views/lessons/18

I found there is a weird issue.
After tapping any row and giving the reviewTextView some content in the DetailViewController, then press save button and get back to the LibraryViewController. The new added review will be shown on the previously tapped row. However, when scrolling the tableView, the new added review randomly appears on the other rows.

Hi! I accidentally cut a bit out of one of my demos that explained this, so thanks very much for letting me know. I’ll get it fixed up :smiley_cat:.

For now, here’s an explanation of what’s going on and how to fix it:

This problem goes back to how cells are reused in table views. So, in the project’s current form, when you are setting up the cells for the data source, the logic for what to do with the reviewLabel looks like this:

if let review = book.review {
  cell.reviewLabel.text = review
  cell.reviewLabel.isHidden = false
}

But the reviewLabel is never hidden again before it is reused for a book that has no review! There’s a few ways you can handle this. You could add an else to that if statement:

if let review = book.review {
  ...
} else {
  cell.reviewLabel.text = nil
  cell.reviewLabel.isHidden = true
}

Or in the BookCell class, override the prepareForReuse method and add the same logic there.

  override func prepareForReuse() {
    reviewLabel.text = nil
    reviewLabel.isHidden = true
  }

If you have a lot of properties on a cell that are handled conditionally, like this reviewLabel is, then prepareForReuse is a great option to keep all of that code together and out of your table view’s data source.

Thank you for your immediate response and detail explanation.
Your course is very practical and helpful.

1 Like

When implementing moveable cells in a UITableViewDiffableDataSource table, is it absolutely necessary to call

apply(snapshot(), animatingDifferences: false)

in case when no cells switched positions? It seems to work with just return, what am I missing? :slight_smile: