【发布时间】:2017-08-22 15:01:26
【问题描述】:
我的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
}
然后我从tableView 和dataSource 中删除约会,如下所示:
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() 似乎也没有区别。
【问题讨论】:
-
你这行的真正意思-:删除第一行后,之后似乎删除了不正确的行?你能解释一下它之后的作用吗?
-
所以当我点击
checkoutButton时,它会调用checkoutButtonTapped。sender.tag是第一次删除行时的正确值。例如,我点击第 2 行的 checkoutButton,sender.tag 为 2,因此从表视图中删除第 2 行。第一次删除后,sender.tag 不再是正确的值例如我可能与第 3 行交互,但sender.tag值将是第 4 行 -
永远不要使用标签来表示索引路径。正如您在此处看到的,在表格视图中删除、插入或移动行会使所有剩余的行带有错误的索引路径标记。
-
@rmaddy 在使用表格视图删除行动画的同时,我还可以使用什么其他方法来正确更新表格视图数据源?
标签: ios swift uitableview