使用sender.tag删除tableview中的行

luk*_*uke 1 uitableview ios swift

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
}
Run Code Online (Sandbox Code Playgroud)

然后我从删除的预定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()
}
Run Code Online (Sandbox Code Playgroud)

我第一次删除约会,它工作正常.该sender.tag值应该是它应该是正确的行从中删除tableView.

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

我在调用reloadData()后尝试调用deleteRows但动画不再出现.beginUpdates()并且endUpdates()似乎没有什么区别都不是.

rma*_*ddy 6

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

不需要使用reloadData标签保持最新的更好的解决方案是indexPath根据按钮的位置确定单元格的按钮.

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
    }
}
Run Code Online (Sandbox Code Playgroud)