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

SwiftUI:如何仅在特定List行禁用swipeActions功能

如何为SwiftUI List的指定行禁用swipeActions?

要实现List部分行启用滑动操作、部分行禁用的效果,核心思路是根据行的标识(比如索引或值)动态控制是否添加swipeActions修饰符。针对你要禁用第50行的需求,具体可以通过两种方式实现:


方式一:使用条件修饰符(代码更简洁)

先给View添加一个自定义扩展,用来实现条件式的视图修饰:

extension View {
    @ViewBuilder
    func applyIf<Content: View>(_ condition: Bool, transform: (Self) -> Content) -> some View {
        if condition {
            transform(self)
        } else {
            self
        }
    }
}

然后在List中通过applyIf判断当前行是否为50,仅当不等于50时才添加滑动操作:

List {
    ForEach(1..<100) { i in
        Text("\(i)")
            .applyIf(i != 50) { view in
                view.swipeActions(edge: .leading) {
                    Button {
                        total += i
                    } label: {
                        Label("Add \(i)", systemImage: "plus.circle")
                    }
                    .tint(.indigo)
                }
            }
            .applyIf(i != 50) { view in
                view.swipeActions(edge: .trailing) {
                    Button {
                        total -= i
                    } label: {
                        Label("Subtract \(i)", systemImage: "minus.circle")
                    }
                }
            }
    }
}

方式二:使用视图分支(更直观)

直接通过if-else分支返回不同的视图,第50行仅返回基础的Text,其余行添加滑动操作:

List {
    ForEach(1..<100) { i in
        if i == 50 {
            Text("\(i)")
        } else {
            Text("\(i)")
                .swipeActions(edge: .leading) {
                    Button {
                        total += i
                    } label: {
                        Label("Add \(i)", systemImage: "plus.circle")
                    }
                    .tint(.indigo)
                }
                .swipeActions(edge: .trailing) {
                    Button {
                        total -= i
                    } label: {
                        Label("Subtract \(i)", systemImage: "minus.circle")
                    }
                }
        }
    }
}

两种方式都能达到禁用第50行滑动操作的目的,你可以根据代码风格偏好选择。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 23:30:55