Swift 5中如何处理Trailing Swipe Action取消时的选中状态恢复
解决UITableView侧滑取消后单元格选中状态不恢复的问题
这个问题本质是UITableView进入侧滑编辑状态时会自动取消单元格选中状态,而取消侧滑(将单元格滑回原位)时,系统不会主动帮你恢复之前的选中状态。我们可以通过监听表格的编辑状态变化,手动补上恢复选中的逻辑。
具体实现步骤:
- 先声明一个变量,用来缓存侧滑操作前处于选中状态的单元格
IndexPath:
private var previouslySelectedIndexPath: IndexPath?
- 实现
UITableViewDelegate的两个方法,监听编辑状态的开始与结束:
func tableView(_ tableView: UITableView, willBeginEditingRowAt indexPath: IndexPath) { // 开始侧滑时,记录当前被操作的单元格是否处于选中状态 if tableView.indexPathForSelectedRow == indexPath { previouslySelectedIndexPath = indexPath } else { previouslySelectedIndexPath = nil } } func tableView(_ tableView: UITableView, didEndEditingRowAt indexPath: IndexPath?) { // 编辑结束后,判断是否需要恢复选中状态 guard let savedIndexPath = previouslySelectedIndexPath, tableView.indexPathForSelectedRow == nil else { return } // 重新选中之前的单元格 tableView.selectRow(at: savedIndexPath, animated: true, scrollPosition: .none) // 清空缓存,避免干扰后续操作 previouslySelectedIndexPath = nil }
- 在你的删除动作回调里,记得清空缓存的
IndexPath(因为单元格已被删除,无需再恢复选中):
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { let deleteAction = UIContextualAction(style: .destructive, title: "") { [weak self] (contextualAction, view, boolValue) in guard let self = self else { return } self.deleteRow(at: indexPath) // 清空缓存的选中路径 self.previouslySelectedIndexPath = nil } deleteAction.image = UIImage(systemName: "trash") let swipeActions = UISwipeActionsConfiguration(actions: [deleteAction]) return swipeActions }
逻辑说明:
- 当用户开始侧滑单元格时,先检查该单元格是否为当前选中项,若是则缓存它的
IndexPath。 - 侧滑操作结束后(无论执行删除还是取消侧滑),如果存在缓存的选中路径且当前表格无选中单元格,就调用
selectRow恢复选中状态。 - 若用户执行了删除操作,在回调里清空缓存,避免后续尝试恢复已不存在的单元格。
内容的提问来源于stack exchange,提问作者Oranutachi
相关产品推荐
相关产品推荐

