我在 TableView 中插入单元格时遇到崩溃。我试过以下链接但不确定是什么问题
下面是我的代码
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return names.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = names[indexPath.row]
return cell
}
数据源代码如下
private var names: [String] = (50...99).map { String($0) }
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
self.appendCells()
}
}
private func appendCells() {
names = (0...49).map { String($0) } + names
customTableView.beginUpdates()
let indexPat = IndexPath(row: names.count - 1, section: 0)
customTableView.insertRows(at: [indexPat], with: .fade)
customTableView.endUpdates()
}
我不明白我在这里错过了什么。对不起,如果我做傻事。如果我需要解释更多,请告诉我。
我收到错误:
原因:'无效更新:第 0 部分中的行数无效。更新后现有部分中包含的行数 (100) 必须等于更新前该部分中包含的行数(50),
最佳答案
问题是您添加到数据模型的值的数量与您添加到 TableView 的行数不匹配。
行:
names = (0...49).map { String($0) } + names
向您的数据模型添加 50 个新值。
但是您随后只告诉 TableView 有一个新行。这就是错误消息中告诉您的内容。
您需要一个循环来构建包含 50 个索引路径的数组。
private func appendCells() {
names = (0...49).map { String($0) } + names
var paths = [IndexPath]()
for row in 0...49 {
let indexPath = IndexPath(row: row, section: 0)
paths.append(indexPath)
}
customTableView.insertRows(at: paths, with: .fade)
}
关于swift - 在 Swift 中插入行崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50102013/