ios - 从 UITableView 中移除动画单元格后更新数据源

标签 ios uitableview swift

我的自定义单元格中有一个删除单元格的按钮。 所以我有一个删除它的委托(delegate)。

View Controller 中的代码:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell =  tableView.dequeueReusableCellWithIdentifier("swipeTableViewCell", forIndexPath: indexPath) as! swipeTableViewCell

    cell.initCell(self, indexPath: indexPath, text: data[indexPath.row])

    return cell
} 

委托(delegate)方法:

func removeCell(indexPath: NSIndexPath){

    data.removeAtIndex(indexPath.row)
    table.beginUpdates()
    table.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
    table.endUpdates()
}

单元格中的代码:

func initCell(handler: handleCells, indexPath: NSIndexPath, text: String) {        
    self.handler = handler
    self.indexPath = indexPath
}

按下按钮:

@IBAction func OnDelButtonClickListener(sender: UIButton) {
    self.handler.removeCell(indexPath)
}

这会删除带有动画的单元格,但不会调用 reloadData,然后单元格就会有错误的 indexPath。 因此,当我按下第二个单元格删除时,错误的单元格被删除。

如果我在 table.endUpdates() 之后调用 reloadData,则没有动画。 如果我调用

let indexSet = NSIndexSet(index: indexPath.section)
self.table.reloadSections(indexSet, withRowAnimation: UITableViewRowAnimation.Automatic)

代替

table.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) 

我没有看到移除动画。

有什么建议吗? 谢谢

最佳答案

查看 Apple 的 UITableViews 编程指南,位于 row deleting section .

我可能在你的代码中遗漏了一些东西,但看起来你实际上并没有删除数据源中与你删除的单元格对应的对象。在删除行之前,尝试使用 removeCell 函数从数据源中删除对象。

func removeCell(indexPath: NSIndexPath){

    // here you delete the object form the datasource

    // after that, you do this
    table.beginUpdates()
    table.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
    table.endUpdates()
}

关于ios - 从 UITableView 中移除动画单元格后更新数据源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30193040/

相关文章:

string - 获取 UITextView 中的当前段落?

ios - 管理登录 IOS App 的用户

ios - 通过向左/向右滑动来最小化对象,同时将另一个对象最大化到屏幕上

ios - 在某些情况下使 superview 响应 subViews Pan Gesture

ios - 在 uitableview, IOS 中突出显示第一个单元格时遇到问题

ios - 在 iOS7 中隐藏 tabBar 显示黑条

Info.plist 中缺少 iOS 9 “fbauth2”

ios - 需要检查我的数组中的特定键值

ios - 多单元格类型 swift 4.2

ios - 如何在不使用 nib 的情况下注册 UIView 以供 UITable View header 重用