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

如何禁用UITableView中特定UITableViewCell的删除选项

问题原因

你当前仅实现了删除操作触发后的业务逻辑,没有限制UITableView可编辑的行范围,系统默认所有行都支持编辑状态,所以所有cell左滑都会显示删除选项。

解决方案

方案1:实现canEditRowAt代理方法(适配系统默认编辑逻辑,改动最小)

新增以下代理方法,仅允许目标类型的行进入编辑状态:

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    // 仅附件类型的行支持编辑(左滑删除)
    return dataSource[indexPath.section].menu == "Attachment"
}

保留你现有的tableView(_:commit:forRowAt:)代码即可,注意修正你现有代码中的笔误:indexpath.section的p需要大写为indexPath.section,否则会编译报错。

方案2:使用滑动动作配置代理(更灵活,支持自定义按钮样式)

如果需要自定义删除按钮的文字、颜色,或者添加更多左滑操作,可以实现以下代理方法,不需要再实现canEditRowAt和commit editingStyle方法:

func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    // 非附件类型的行不返回任何滑动操作,不会出现左滑按钮
    guard dataSource[indexPath.section].menu == "Attachment" else {
        return nil
    }
    // 创建删除操作
    let deleteAction = UIContextualAction(style: .destructive, title: "删除") { [weak self] (_, _, completion) in
        self?.attachmentList.remove(at: indexPath.row)
        tableView.deleteRows(at: [indexPath], with: .automatic)
        completion(true)
    }
    return UISwipeActionsConfiguration(actions: [deleteAction])
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 01:06:01