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

SwiftUI ForEach循环内修改指定按钮颜色及let常量不可修改问题解决

问题解决方法

错误原因

  • ForEach 遍历闭包中传入的 workout 是临时只读常量,本身不允许直接修改
  • 你当前定义的 workouts 数组没有添加 SwiftUI 状态修饰符,即便修改了数组内容也无法触发UI刷新

修复后代码

struct Workout: Identifiable {
    var id = UUID()
    var name: String
    var isActive: Bool
}

struct Workout_builder: View {
    // 添加@State修饰符,让SwiftUI监听数组的状态变化,改动后自动刷新UI
    @State var workouts = [
        Workout(name: "Bench Press", isActive: false),
        Workout(name: "Shoulder Press", isActive: false),
        Workout(name: "Incline Press", isActive: false),
        Workout(name: "Lateral Raises", isActive: false),
        Workout(name: "Tricep Cable", isActive: false),
    ]
        
    var body: some View {
        VStack {
            List {
                // 遍历数组的绑定对象,拿到可读写的元素引用
                ForEach($workouts) { $workout in
                    Button(action: {
                        // 直接修改绑定的元素属性
                        workout.isActive.toggle()
                    }) {
                        Text(workout.name)
                            .foregroundColor(.black)
                            .background(workout.isActive ? Color.white : Color.blue)
                    }
                }
            }
        }
    }
}

兼容旧版SwiftUI的写法

如果你使用的SwiftUI版本不支持直接对Identifiable数组做绑定遍历,可以改用索引遍历的方式实现:

ForEach(workouts.indices, id: \.self) { index in
    Button(action: {
        workouts[index].isActive.toggle()
    }) {
        Text(workouts[index].name)
            .foregroundColor(.black)
            .background(workouts[index].isActive ? Color.white : Color.blue)
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 21:24:03