【发布时间】:2026-01-19 00:20:08
【问题描述】:
我正在用UITableViewin Swift 5 进行实验。
我想插入和删除行。
添加其他行时,我的表崩溃了。第一个插入工作正常。
class ViewController: UITableViewController {
var items = [Int]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.backgroundColor = .white
tableView.tableFooterView = UIView()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "CELL_ID")
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.addMoreRows([1,2,3,4,5])
}
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
self.addMoreRows([6,7,8,9,10])
}
}
private func addMoreRows(_ data: [Int]) {
self.items.append(contentsOf: data)
var indexPaths = [IndexPath]()
for i in 0...items.count - 1 {
indexPaths.append(IndexPath(row: i, section: 0))
}
tableView.insertRows(at: indexPaths, with: .left)
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CELL_ID", for: indexPath)
cell.textLabel?.text = "Cell #\(indexPath.row)"
return cell
}
}
由于未捕获的异常而终止应用程序 'NSInternalInconsistencyException',原因:'无效更新:无效 第 0 节中的行数。包含在第 0 节中的行数 更新后的现有节(10)必须等于 更新前该部分中包含的行 (5),加号或减号 从该部分插入或删除的行数(插入 10 行, 0 已删除)加或减移入或移出的行数 该部分(0 移入,0 移出)。'
【问题讨论】:
标签: ios swift uitableview