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

如何禁用UITableViewCell左滑至屏幕边缘自动触发删除操作?

禁用UITableViewCell左滑至边缘自动触发删除的方法

嘿,这个需求我之前做项目时刚好碰到过,其实分两种常见场景来处理,具体看你用的是哪个版本的API:

情况1:iOS 11及以后(使用UIContextualAction)

这是最简单的情况!iOS 11引入了UISwipeActionsConfiguration,它专门提供了一个属性来控制“滑到底自动执行第一个操作”的行为:

在实现trailingSwipeActionsConfigurationForRowAt代理方法时,创建完你的删除action后,把配置的performsFirstActionWithFullSwipe设为false即可:

func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    let deleteAction = UIContextualAction(style: .destructive, title: "删除") { [weak self] (action, view, completionHandler) in
        // 这里写你的删除逻辑,比如删除数据、刷新表格
        self?.yourDataSource.remove(at: indexPath.row)
        tableView.deleteRows(at: [indexPath], with: .automatic)
        completionHandler(true)
    }
    
    let configuration = UISwipeActionsConfiguration(actions: [deleteAction])
    // 关键:禁用滑到底自动触发
    configuration.performsFirstActionWithFullSwipe = false
    return configuration
}

这样用户左滑只会显示删除按钮,必须点击按钮才会执行删除,滑到屏幕边缘也不会自动触发。

情况2:iOS 11之前(使用UITableViewRowAction)

对于更早的系统版本,我们需要通过两个代理方法配合来实现:

  1. 首先,实现editingStyleForRowAt返回.none,关闭系统默认的编辑删除样式:
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
    return .none
}
  1. 然后在editActionsForRowAt里自定义删除按钮,并且在handler里手动处理删除逻辑:
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    let deleteAction = UITableViewRowAction(style: .destructive, title: "删除") { [weak self] (action, indexPath) in
        // 执行删除操作
        self?.yourDataSource.remove(at: indexPath.row)
        tableView.deleteRows(at: [indexPath], with: .automatic)
    }
    return [deleteAction]
}

这样设置后,系统不会启用默认的“滑到底删除”行为,用户必须点击删除按钮才能触发操作。

额外提示

如果你只是想完全禁用左滑删除功能(连滑出按钮都不想有),那只需要在editingStyleForRowAt里返回.none,并且不要实现任何滑动action的代理方法就可以了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:21:32