You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift 5中如何处理Trailing Swipe Action取消时的选中状态恢复

解决UITableView侧滑取消后单元格选中状态不恢复的问题

这个问题本质是UITableView进入侧滑编辑状态时会自动取消单元格选中状态,而取消侧滑(将单元格滑回原位)时,系统不会主动帮你恢复之前的选中状态。我们可以通过监听表格的编辑状态变化,手动补上恢复选中的逻辑。

具体实现步骤:

  1. 先声明一个变量,用来缓存侧滑操作前处于选中状态的单元格IndexPath:
private var previouslySelectedIndexPath: IndexPath?
  1. 实现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
}
  1. 在你的删除动作回调里,记得清空缓存的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 14:57:50