How to update a table cell using diffable UITableView

前端 未结 1 1123
孤城傲影
孤城傲影 2021-01-06 08:58

I\'m using the new NSDiffableDataSourceSnapshot and UITableViewDiffableDataSource with a UITableView. I\'m having no problems building the table but I\'m having problems upd

相关标签:
1条回答
  • 2021-01-06 09:51

    I have had similar problems and after a lot of debugging and trying out different things I've come to the conclusion that I don't think you should be using reloadItems. reloadItems doesn't actually seem to do anything from my testing. The cell provider always provides the old data and if you have a hash function based on an identifier and an equatable function that checks for equality on things other than the identifier, you get an error.

    There are two things that you can try

    1. if you really want to use reload items in the cellProvider instead of using the data provided by the closer, use your own data source as the source of truth to lay out the cells. (this sort of defeats the purpose of diffableDataSource in my opinion though). You end up missing out on some of the great functionality of DiffableDataSource

    2. instead of writing code like this:

    var snapshot = tableView.snapshot()
    let item = items[indexPath.row]
    snapshot.reloadItems([item]) 
    

    you can do this

    let snapshot: NSDiffableDataSourceSnapshot<Section,Item> = .init() 
    // assuming wherever you're storing your data is already updated 
    snapshot.appendItems([items])
    dataSource.apply(snapshot)  
    

    This should refresh only the items in the snapshot that have changes. From my understanding, the current snapshot of the tableView is compared with the newly created snapshot and only items that are different should be updated. I could be wrong here, but this is what has worked for me.

    Other suggestions I've seen:

    • write your has function combining all the values that can change in the view ex.
    func hash(into hasher: inout Hasher) {
      hasher.combine(id)
      hasher.combine(name)
      hasher.combine(title)
    }
    

    however if you go this route this means that reloadItems will throw an error reporting that this doesn't exist in the data source so you'll have to add this and delete the old data manually

    0 讨论(0)
提交回复
热议问题