我是编程和 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)
}
}
}