Я пытаюсь использовать 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
, это вызовет sh:
Завершение приложения из-за к необработанному исключению «NSInternalInconsistencyException», причина: «Неверное обновление: неверное количество разделов. Количество разделов, содержащихся в табличном представлении после обновления (1), должно быть равно количеству разделов, содержащихся в табличном представлении до обновления (1), плюс или минус количество вставленных или удаленных разделов (1 вставлено, 0 удалено). '