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

Swift4下如何禁用UITableView侧滑时自动触发删除操作?

解决左滑表格行自动触发第一个操作的问题

这个问题我之前也踩过坑!默认情况下用旧的滑动操作API实现时,完全左滑确实会自动触发第一个定义的操作,要禁用这个行为,你可以切换到iOS11之后推出的UISwipeActionsConfiguration API来实现——它刚好提供了专门控制这个行为的配置项,完美适配Swift4。

下面是具体的实现步骤:

  • 替换旧的editActionsForRowAt方法,改用trailingSwipeActionsConfigurationForRowAt(如果是左侧滑动操作就用leadingSwipeActionsConfigurationForRowAt)
  • 创建UISwipeActionsConfiguration实例时,设置performsFirstActionWithFullSwipe = false,这一行就是禁用自动触发的关键

给你贴个Swift4的完整示例代码:

override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    // 创建删除操作(带图标无文字)
    let deleteAction = UIContextualAction(style: .destructive, title: nil) { [weak self] (action, view, completionHandler) in
        // 这里写你的删除逻辑
        self?.tableView.deleteRows(at: [indexPath], with: .automatic)
        completionHandler(true)
    }
    deleteAction.image = UIImage(named: "delete_icon") // 设置你的删除图标
    
    // 可以按需添加更多操作,比如编辑
    let editAction = UIContextualAction(style: .normal, title: nil) { [weak self] (action, view, completionHandler) in
        // 这里写你的编辑逻辑
        self?.showEditDialog(for: indexPath)
        completionHandler(true)
    }
    editAction.image = UIImage(named: "edit_icon") // 设置你的编辑图标
    editAction.backgroundColor = .systemBlue
    
    // 创建配置并禁用完全滑动自动触发
    let swipeConfig = UISwipeActionsConfiguration(actions: [deleteAction, editAction])
    swipeConfig.performsFirstActionWithFullSwipe = false // 核心配置
    
    return swipeConfig
}

补充说明

为什么这个方法可行?因为UISwipeActionsConfiguration是苹果为了替代旧滑动API推出的新方案,它提供了更灵活的自定义空间,performsFirstActionWithFullSwipe这个布尔值就是专门用来控制“完全滑动时是否自动执行第一个操作”的,设为false后,用户完全左滑只会展开所有操作按钮,不会自动触发任何动作。

如果因为兼容需求必须使用旧的editActionsForRowAt API,那很遗憾,旧API没有官方的禁用方式,只能通过自定义手势等hack手段实现,但稳定性差不推荐,所以优先建议用新API解决问题。

内容的提问来源于stack exchange,提问作者LarsGvB

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 09:03:24