我有2D数组var students = [[Student]]
我需要遵守这个数组应该始终保持3在内存中所以当这个数组插入新的itme然后从旧的顶部删除
我必须以这种方式插入数组
self.students.append(student) //Update students property
并尝试使用此行但是
当我使用此行删除项目时,tableview
无法顺利更新
self.students.removeFirst()
那么如何从表格视图中顺利滚动
从顶部删除数组项目注意数组挂钩表视图
func numberOfSections(in tableView: UITableView) -> Int {
return self.students.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return students[section].count
}
答案 0 :(得分:2)
如果尺寸固定,最好不要删除物品。
使用包含三个项目的固定大小数组,其中一些项目可能为空,另外还有一个单独的count
和firstIndex
变量。实际上,您的数组变为Circular Queue:
var students : [[Student]] = [[], [], []]
var count = 0;
var firstIndex = 0;
// Adding a new item
students[(firstIndex+count) % students.count] = newItem
if (count != 3) {
count++
} else {
firstIndex = (firstIndex+1) % students.count
}
// Iterating the array
for var i in (0..<students.count) {
let currentStudent = students[(firstIndex+i)%students.count]
...
}
部分数量为count
:
func numberOfSections(in tableView: UITableView) -> Int {
return count
}
唯一的技巧是找出用于给定索引路径的索引:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return students[(section + firstRow) % students.count].count
}
let actualIndex = (indexPath.section + firstIndex) % students.count
答案 1 :(得分:1)
使用
students.removeFirst()
用于删除第一个元素和
students.removeLast()
用于删除最后一个元素。
如果要在某个索引使用时将其删除,
students.remove(at: theindexyouwant)
如果您想在删除期间使用动画:
tableview.deleteRowsAtIndexPaths(tRemove, withRowAnimation: .Left)