如何避免重新加载整个表,从而中断滚动



我想将元素的数量限制为三个。当我加上第四个元素时,第一个元素应该消失。

如果我想继续滚动,我应该通过调用deleteRowsAtIndexPaths来告诉UITableView我正在删除整个section零中的行。之后,我需要告诉UITableView,您将在第三section(部分索引 2(插入一堆行。

这样,您将能够避免重新加载整个表,从而中断滚动。

但不幸的是,它对我不起作用。

给我这个错误:

'attempt to delete row 3 from section 2, but there are only 1 sections before the update'

法典:

//scrolling down time calling this method
func oldestState(){
//var students : [[Student]]? = [[],[],[]]
let data = getdata()
self.students?[(self.firstIndex+self.count) % (self.students?.count)!] = data
if (self.count != 3) {
self.count += 1
} else {
self.firstIndex = (self.firstIndex+1) % (self.students?.count)!
}
self.newsFeedTableView.beginUpdates()
let indexPathsDeleted = (0..<(data
.count)).map { IndexPath(row: $0, section: (self.students?.count)! - 1) }
self.newsFeedTableView.deleteSections([0], with: UITableViewRowAnimation.automatic)
self.newsFeedTableView.deleteRows(at: indexPathsDeleted, with: UITableViewRowAnimation.automatic)
self.newsFeedTableView.endUpdates()
self.newsFeedTableView.beginUpdates()
let indexPathsInsert = (0..<(data
.count)).map { IndexPath(row: $0, section: (self.students?.count)! - 1) }
self.newsFeedTableView.insertSections([2], with: UITableViewRowAnimation.automatic)
self.newsFeedTableView.insertRows(at: indexPathsInsert, with: UITableViewRowAnimation.automatic)
self.newsFeedTableView.endUpdates()
}

func getdata() -> [Student]{
var _students = [Student]()
for i in  itemNumber..<(itemNumber + 4) {
let student = Student()
student.name = "(i)"
print("adding student roll number : (student.name)")
_students.append(student)
}
itemNumber  +=  4
return _students
}
}

这是完整的 Git 代码:

我不知道表视图的数据源的行为,但是从错误中,它清楚地告诉我们,您只有一个部分,因此您无法处理第2节,因为没有第2节,您只能处理第0节。 您可以删除整行,并在第 0 节中添加行,此外,您应该处理 self.students 数组,让它与表视图行匹配,否则它会崩溃。

更新:

此提交解决了表滚动问题

我已经更正了,这个版本。

此提交解决了表格滚动变得生涩的问题

我已经更正了,这个版本。

最新更新