gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 05:55:53 24 4
gpt4 key购买 nike

我的 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/

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