【问题标题】:2D array remove First not Smooth updating tableview2D 数组删除 First not Smooth 更新 tableview
【发布时间】:2017-08-01 13:42:50
【问题描述】:

我有 2D 数组 var students = [[Student]] 我需要使这个数组在内存中始终保持 3,所以当这个数组插入新的时,然后从顶部从旧的删除

我必须这样插入数组

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
}

更新:

【问题讨论】:

标签: ios arrays swift uitableview


【解决方案1】:

使用固定的上限尺寸,您最好不要删除项目。

使用由三个项目组成的固定大小的数组,其中一些可能为空,以及一个单独的 countfirstIndex 变量。实际上,您的数组变成了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

【讨论】:

  • 非常感谢您在我的项目中尝试您的回答并回复您
  • 它工作正常,但是当尝试将第 4 项附加到 a 数组时,流线 (firstIndex+count) % students.count 给我日志 3fatal error: Index out of range
  • @NazmulHasan 这告诉我 students.count 大于 3,这绝不应该发生,因为 students.count 固定为 3,并且任何正数 mod % 3 是 0、1 或2.append要替换成上面循环添加的代码。
  • 谢谢,基本上它从 1 到 3 工作正常,但是当向数组添加第 4 项时,tableView 滚动不会下降,因此不显示第 4 项另一方面日志查看数组数据已更新。你可以查看我的问题更新部分图片和示例代码github.com/nazmulkp/PagginationSwift3
  • @NazmulHasan 我以为您想将元素数量限制为三个。当你添加元素四时,元素一应该消失,对吧?如果您希望滚动继续正常,您应该通过调用deleteRowsAtIndexPaths 告诉UITableView 您正在删除整个零节中的行。之后,您需要告诉UITableView,您将在第三部分(部分索引 2)插入一堆行。这样您就可以避免重新加载整个表格,破坏滚动。
【解决方案2】:

使用 students.removeFirst()用于删除第一个元素和 students.removeLast() 用于删除最后一个元素。

如果你想在某个索引使用时删除它, students.remove(at: theindexyouwant)

编辑:

如果您想在删除期间使用动画: tableview.deleteRowsAtIndexPaths(tRemove, withRowAnimation: .Left)

【讨论】:

  • 当我使用self.students.removeFirst()删除项目时,tableview 无法顺利更新
  • tableview.deleteRowsAtIndexPaths 不应该工作,因为它是二维数组
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-06-09
  • 1970-01-01
  • 2012-01-10
  • 1970-01-01
  • 2018-12-21
  • 1970-01-01
  • 2015-10-03
相关资源
最近更新 更多