SwiftUI - 更改 ForEach 中的结构数据集?

2024-02-16

我是编程和 SwiftUI 的新手,我正在制作这个应用程序,用户可以选择这些标记为 A-D 的按钮。他们可能会选择超过 1 个,我希望当他们单击按钮时,背景颜色会从灰色变为绿色。但是,如果我将底部代码中的“// Here”替换为

Data.Selected = true
Data.Colour = .green

我收到一条错误消息“无法分配给属性:‘Data’是‘let’常量”。我明白这意味着什么,但我不知道如何将 Data 更改为 var。我尝试在“数据输入”前面输入 var,但收到此错误“一行上的连续语句必须用 ';' 分隔”。我可以直接修改Data/ButtonsData吗?或者有解决方法吗?

struct Buttons: Hashable {
    var Crit: String
    var Selected: Bool
    var Colour: Color
}

var ButtonsData = [
    Buttons(Crit: "A", Selected: false, Colour: Color(.systemGray4)),
    Buttons(Crit: "B", Selected: false, Colour: Color(.systemGray4)),
    Buttons(Crit: "C", Selected: false, Colour: Color(.systemGray4)),
    Buttons(Crit: "D", Selected: false, Colour: Color(.systemGray4))
]

struct CritView: View {
    
    @Binding var CritBoard: Bool
    @Binding var BackgroundColor: Color
    
    var body: some View {
        ZStack(alignment: .topLeading) {
            
            ScrollView(.vertical, showsIndicators: false) {
                HStack(spacing: 15) {
                    ForEach(ButtonsData, id: \.self) { Data in
                        Button(action: {
                          // HERE
                        }) {
                            Text(Data.Crit)
                                .font(.system(size: 30))
                        }
                        .frame(width: 65, height: 55)
                        .background(Data.Colour)
                        .cornerRadius(10)
                    }
                }
                .padding(.top, 50)
            }
            .frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height/8)
            .padding(.bottom, UIApplication.shared.windows.first?.safeAreaInsets.bottom)
            .background(Color(.white))
            .cornerRadius(25)
            
            Button(action: {
                self.CritBoard.toggle()
                self.BackgroundColor = .white
            }) {
                Image(systemName: "xmark").foregroundColor(.black)
            }.padding(25)
        }
    }
}

这是可能的解决方案 - 创建索引/值元组数组并按索引修改原始容器中的数据:

ForEach(Array(ButtonsData.enumerated()), id: \.element) { i, Data in
    Button(action: {
      ButtonsData[i].Selected = true
      ButtonsData[i].Colour = .green
    }) {
        Text(Data.Crit)
            .font(.system(size: 30))
    }
    .frame(width: 65, height: 55)
    .background(Data.Colour)
    .cornerRadius(10)
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

SwiftUI - 更改 ForEach 中的结构数据集? 的相关文章

随机推荐