我试着使用UITableViewDiffableDataSource
class SecondViewController: UIViewController {
enum Section {
case main
}
struct Model: Hashable {
let title: String
}
var tableView: UITableView!
var dataSource: UITableViewDiffableDataSource<Section, Model>!
override func viewDidLoad() {
super.viewDidLoad()
tableView = UITableView(frame: view.bounds)
view.addSubview(tableView)
tableView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
view.layoutIfNeeded()
dataSource = UITableViewDiffableDataSource<Section, Model>(tableView: tableView, cellProvider: { (tableView, indexPath, item) -> UITableViewCell? in
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = item.title
return cell
})
var snapshot = NSDiffableDataSourceSnapshot<Section, Model>()
snapshot.appendSections([.main])
snapshot.appendItems([Model(title: "1")], toSection: .main)
dataSource.apply(snapshot)
}
}如果在创建view.layoutIfNeeded()之前使用dataSource,它将崩溃:
由于
异常“NSInternalInconsistencyException”终止应用程序,原因:“无效更新:无效节数。更新(1)后表视图中包含的节数必须等于更新(1)之前表视图中包含的节数,加上或减去插入或删除的节数(插入或删除的节数)。”
。
发布于 2020-07-25 03:20:05
在使用来自UITableView的结果填充PassthroughSubject时,在显示UIViewController时,我也遇到了同样的问题。
动画更新对我来说非常重要,所以我的解决方法是首先“优化”DiffableDataSource,在初始化后立即创建快照,追加我想要的部分,用空数组追加项目,并将快照应用于animatingDifferences: false。
之后,我能够应用无问题的数据动画快照。
发布于 2021-12-15 22:48:51
我也遇到了同样的问题。通常,在iOS 14上,在表视图的数据源设置之前导致布局会导致崩溃。
一旦创建了表视图,就可以通过设置数据源来修复这些崩溃。如果您想要动画您的初始快照,那么首先设置一个空快照,然后使用animatingDifferences: true填充的快照。
发布于 2022-05-19 05:30:46
同样的问题,我发现即使没有动画,一些用户在生产中仍然会崩溃。
当我在setupUI in viewDidLoad,DispatchQueue.main.async帮助我解决这个问题
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
var snapshot = NSDiffableDataSourceSnapshot<Section, Row>()
snapshot.appendSections([...])
snapshot.appendItems([...], toSection: .main)
dataSource.apply(snapshot, animatingDifferences: true, completion: nil)
}更具体地说,仅仅将animatingDifferences设置为false仍然会崩溃。此崩溃仅发生在iOS 15.0.0和iOS 15.0.1上。

https://stackoverflow.com/questions/60789365
复制相似问题