我使用Swift 3。 我有7行的UITableView:
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
}
func tableView(_ tableView:UITableView, numberOfRowsInSection section:Int) -> Int
{
return 7
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
if (IndexPath.row == 6)
{
tableView.beginUpdates()
var index = IndexPath(row: 7, section: 0)
tableView.insertRows(at: [index], with: UITableViewRowAnimation.automatic)
tableView.endUpdates()
}
}
当我滚动到表格中的最后一个单元格时,我想添加其他单元格。 但我得到了这个错误:
无效更新:第0部分中的行数无效 更新(7)后必须包含在现有部分中的行 等于之前该部分中包含的行数 update(7),加上或减去插入或删除的行数 该部分(1个插入,0个删除)和加号或减号的数量 移入或移出该部分的行(0移入,0移出)。
答案 0 :(得分:1)
当您从tableView插入或删除任何行时,应更新数据源,并确保对象数保持等于tableView中的行数
func tableView(_ tableView:UITableView, numberOfRowsInSection section:Int) -> Int {
return dataSource.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if (IndexPath.row == 6) {
tableView.beginUpdates()
var index = IndexPath(row: 7, section: 0)
let newObject = // create new model object here
dataSource.insert(newObject, at: 7)
tableView.insertRows(at: [index], with: UITableViewRowAnimation.automatic)
tableView.endUpdates()
}
}