我正在使用新的UITableViewDiffabledatasource和NSFetchedResultController设置tableView。
插入和删除已正确处理。但是,当某个项目被更新(例如其中一项属性已更新)并且显示该项目的单元格应该被更新时,它不会被更新。
如何确保UITableViewDiffabledatasource看到更改并触发单元格刷新?
添加我正在使用的代码:
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = dataSource
}
func makeDataSource() -> UITableViewDiffableDataSource<String,nsmanagedobjectid> {
let reuseIdentifier = String(describing: RegisterTableCell.self)
let dataSource = UITableViewDiffableDataSource<String,nsmanagedobjectid>(
tableView: tableView,cellProvider: { tableView,indexPath,objectID in
let cartItem = try! self.container.viewContext.existingObject(with: objectID) as! CartItem
let cell = tableView.dequeueReusableCell(
withIdentifier: reuseIdentifier,for: indexPath
) as! RegisterTableCell
cell.count.text = String(format: "%@",cartItem.count ?? "0")
cell.label.text = cartItem.name
cell.price.text = self.priceFormatter.string(from: Nsnumber(value: cartItem.totalPrice()))
return cell
}
)
dataSource.defaultRowAnimation = .left
return dataSource
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>,didChangeContentWith snapshot: NSDiffableDataSourcesnapshotReference) {
updateUI()
let diffablesnapshot = snapshot as NSDiffableDataSourcesnapshot<String,nsmanagedobjectid>
dataSource.apply(diffablesnapshot,animatingDifferences: true,completion: nil)
}