gpt4 book ai didi

ios swift : UITableViewCell's tag is not updated after consecutive delete of cells

转载 作者:行者123 更新时间:2023-11-30 13:03:44 25 4
gpt4 key购买 nike

我已经根据传递的索引实现了任何行的删除功能。

每个单元格都有一个按钮来启动该行的删除。我使用 cell.tag 来检测行并传递给使用indexPath 和deleteRowAtIndexPaths(...) 的删除函数。

现在,当我继续删除第 0 行时,就会出现问题。最初,它会正确删除。第 0 行消失了。第 1 行替换第 0 行。现在,如果我再次删除第 0 行,它将删除当前的第 1 行。

我理解的原因是 cell.tag 没有更新。我到底做错了什么?问题不一致。如果我在删除之间等待,那就可以了。如果我删除一行又一行。它继续删除其他一些行。

我现在应该如何进行?我已经搜索过这个问题,但找不到合适的解决方案或指南?

以下是主要代码

// Typical code having Programmatic UITableView
// ...

func addTestEvent(cell: MyCell) {
func onSomeAction() {
dispatch_async(dispatch_get_main_queue(), {
self.removeRow(cell.tag)
})
}

...
// onSomeAction() called on click on the button
}


func test(cell: MyCell) -> () {
...
addTestEvent(cell)

}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier( NSStringFromClass(MyCell), forIndexPath: indexPath) as! MyCell
cell.tag = indexPath.row
cell.test = { (cell) in self.test(cell) }
return cell
}


func removeRow(row: Int) {
let indexPath = NSIndexPath(forItem: row, inSection: 0)
tableView.beginUpdates()
posts.removeAtIndex(row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
tableView.endUpdates()
}

最佳答案

关键点是不要使用cell.tag来标识cell。而是直接使用细胞。谢谢Vadian对于 comment 。将 indexPath 保留在单元格标记中并不是一个好习惯。现在我知道为什么了!

这个答案给了我解决问题的主要提示。 https://stackoverflow.com/a/29920564/2369867

// Modified pieces of code. Rest of the code remain the same.

func addTestEvent(cell: MyCell) {
func onSomeAction() {
dispatch_async(dispatch_get_main_queue(), {
self.removeRow(cell)
})
}
// ...
// onSomeAction() called on click on the button
}

func removeRow(cell: UITableViewCell) {
let indexPath = tableView.indexPathForRowAtPoint(cell.center)!
let rowIndex = indexPath.row
// ...
}

关于ios swift : UITableViewCell's tag is not updated after consecutive delete of cells,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39622154/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com