点击UIAlertAction后删除UITableView单元格,却提前删除问题求助
问题原因
你的代码把删除单元格的逻辑直接写在了弹窗展示代码的前面,且没有绑定到确认按钮的点击事件上,导致一点击删除按钮就先执行了删除操作,之后才弹出确认弹窗。另外还多写了一行alert.dismiss(animated: true, completion: nil),这行代码在弹窗还没展示时就调用,完全没必要。
修复后的代码
@IBAction func binButton(_ sender: Any) { let subtitleString = NSAttributedString(string: "Are you sure to delete?", attributes: [ NSAttributedString.Key.font : UIFont(name: "SFProText-Regular", size: 13) ?? .systemFont(ofSize: 13), NSAttributedString.Key.foregroundColor: UIColor.white ]) let alert = UIAlertController(title: "Take Attention", message: "", preferredStyle: .alert) alert.setValue(subtitleString, forKey: "attributedMessage") alert.view.subviews.first?.subviews.first?.subviews.first?.backgroundColor = UIColor(named: "AlertColor") alert.view.tintColor = UIColor.white let cancelAlert = UIAlertAction(title: "No", style: .default, handler: nil) cancelAlert.setValue(UIColor(named: "Orange"), forKey: "titleTextColor") // 把删除逻辑移到Yes按钮的点击回调里 let actionDelete = UIAlertAction(title: "Yes", style: .default) { [weak self] _ in guard let self = self, let selectedRows = self.usersTableView.indexPathsForSelectedRows else { return } // 1. 收集要删除的元素 var items = [String]() for indexPath in selectedRows { items.append(self.userName[indexPath.row]) } // 2. 从数据源删除对应元素 for item in items { if let index = self.userName.firstIndex(of: item) { self.userName.remove(at: index) } } // 3. 更新表格UI self.usersTableView.beginUpdates() self.usersTableView.deleteRows(at: selectedRows, with: .automatic) self.usersTableView.endUpdates() } actionDelete.setValue(UIColor(named: "companyTextColor"), forKey: "titleTextColor") alert.addAction(cancelAlert) alert.addAction(actionDelete) self.present(alert, animated: true, completion: nil) }
关键修改点
- 移除了多余的
alert.dismiss(animated: true, completion: nil)代码 - 将删除单元格的完整逻辑移入"Yes"按钮的
handler闭包中,确保只有用户点击确认后才执行删除操作 - 添加
[weak self]避免循环引用,保证内存安全
内容的提问来源于stack exchange,提问作者Willian M.
相关产品推荐
相关产品推荐

