ios - 使用 sender.tag 时删除 TableView 中的行

标签 ios swift uitableview

我的 tableView cellForRowAtIndexPath 看起来像这样:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: CheckoutAppointmentCell.reuseIdentifier) as! CheckoutAppointmentCell
    cell.appointment = appointments[indexPath.row]
    cell.checkoutButton.tag = indexPath.row
    cell.checkoutButton.addTarget(self, action: #selector(checkoutButtonTapped), for: .touchUpInside)
    return cell
}

然后我从 tableViewdataSource 中删除约会,如下所示:

func checkoutButtonTapped(sender: UIButton) {
    appointments.remove(at: sender.tag)
    print(sender.tag)
    //self.tableView.beginUpdates()
    self.tableView.deleteRows(at: [IndexPath(row:sender.tag, section: 0)], with: .automatic)
    //self.tableView.endUpdates()
}

我第一次删除约会时,它运行良好。 sender.tag 的值是它应该的值,并且从 tableView 中删除了正确的行。

删除第一行后,似乎删除了不正确的行。

我尝试在调用 deleteRows 之后调用 reloadData(),但动画不再出现。 beginUpdates()endUpdates() 似乎也没有区别。

最佳答案

使用标签来跟踪索引路径是一种常见但非常糟糕的做法。它在任何允许删除、插入或移动行的 TableView 中失败,因为剩余的单元格现在具有无效标记,除非使用 reloadData 完全重新加载 TableView 。

不需要使用 reloadData 来保持标记最新的更好的解决方案是根据按钮的位置。

func checkoutButtonTapped(sender: UIButton) {
    let hitPoint = sender.convert(CGPoint.zero, to: tableView)
    if let indexPath = tableView.indexPathForRow(at: hitPoint) {
        // use indexPath to get needed data
    }
}

关于ios - 使用 sender.tag 时删除 TableView 中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45800273/

相关文章:

ios - 获取NSData而不是NSXMLParser

ios - 苹果可以在我的应用程序中批准信用卡表格吗?

ios - 如何判断有多少 UITableViewCell 是可见的

ios - 如何从未捕获的异常处理函数中调用实例方法?

ios - 在 Storyboard 上使用内置的 UITabBarItem 图像

swift - 在没有物理或 SKActions 的情况下使用 SpriteKit

swift - 如何快速按钮突出显示和突出显示颜色为红色

iphone - deleteRowsAtIndexPaths 崩溃

ios - DLNA - 适用于 iOS 的 DMC

ios - 用于创建手机身份验证凭据的验证 ID 无效 iOS