【发布时间】:2020-06-23 14:12:39
【问题描述】:
我是编程和 SwiftUI 的新手,我正在制作这个应用程序,用户可以在其中选择标记为 A-D 的这些按钮。他们可能会选择超过 1 个,我希望当他们点击按钮时,背景颜色会从灰色变为绿色。但是,如果我将底部代码中的“// Here”替换为
Data.Selected = true
Data.Colour = .green
我收到一条错误消息,提示“无法分配给属性:'Data' 是 'let' 常量”。我明白这意味着什么,但我不知道如何将 Data 更改为 var。我尝试在“数据输入”前键入 var,但出现此错误,而不是“一行上的连续语句必须用 ';' 分隔”。无论如何我可以直接修改数据/按钮数据吗?或者有什么解决方法?
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)
}
}
}
【问题讨论】: