删除行UITableView索引问题 [英] delete row UITableView index issue

查看:85
本文介绍了删除行UITableView索引问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用下面的代码删除tableview中的一行。首先,我从数组中删除对象,然后使用以下代码从tableview中删除:

I'm using the code below to delete a row in my tableview. First I delete the object from my array and then from the tableview using this code:

let i = IndexPath(item: rowNum, section: 0)
myArray.remove(at: rowNum)
myTableView.deleteRows(at: [i], with: UITableViewRowAnimation.left)

但是,如果我之后删除了另一行,则不会删除我想要删除的行。问题是,即使我删除了tableview中的第一项(例如索引0),单击新的第一行将返回索引1 ...这是错误的,并删除第二行。删除第一行后,顶部的新行应该有一个0的索引。

However, if I delete another row right after, not the row I wanted to be deleted gets deleted. The issue is, even though I deleted the first item in the tableview (e.g. index 0), clicking on the new first row returns index 1... which is wrong, and deletes the second row. After deleting the first row the new row at the top should have an index of 0.

我可以通过以下方式解决这个问题:

I can solve this problem by doing:

mTableView.reloadData()

但是这似乎是错的......我不应该再次重新加载所有数据。

but this seems wrong... I shouldn't have to reload all the data again.

我还能做什么?

编辑:我在tableviewcell中有一个自定义按钮我要按删除行 - 不要滑动。

I have a custom button in my tableviewcell I am pressing to delete the row - not swiping.

推荐答案

问题

您遇到的问题是您在按钮上设置的标记,按钮标记在删除行时不会更改,因为它的全部细胞没有重新加载。 $ b $猜猜你在 cellforRowIndexpath 中设置标签你尝试将标记放在 tableWillDisplayCell

The problem in you case is the Tag you are setting on the Button , button Tag is not changed when you are deleting the Rows , as its the All Cell is not Reloaded. i guess you are setting tag in cellforRowIndexpath you try with putting tag on button in tableWillDisplayCell

最佳方式如下。

解决方案

您可以通过其他方式获得 IndexPath

you can get the IndexPath in other way


假设您的视图层次结构是

Suppose if your view hierarchy is

UITableViewCell-> contentView - > button

UITableViewCell-> contentView -> button

按钮点击方式

 if let cell = sender.superview?.superview as? UITableviewCell{
        let indexPath = myTableView.indexPath(for: cell)
    // Now delete the table cell
    myArray.remove(at: indexPath.row)
    myTableView.beginUpdates()
    myTableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.left)
    myTableView.endUpdates()
}

我希望这对你有用。

这篇关于删除行UITableView索引问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆