【发布时间】:2021-03-12 12:22:48
【问题描述】:
我在struct 内的代码中有一个@State 布尔值,我有一个toggle()s 按钮。但是,我也想在我的其他视图中使用该变量。所以我需要把它放在struct 外面,这样我就可以在其他地方使用它了。我的问题是我现在如何改变它的价值?以前我的button 的操作toggled 它。现在怎么改?
这是我的代码:
struct ContentView: View {
@State var checked: Bool = false
var body: some View {
HStack {
Button(action: {checked.toggle()}) {
Image(systemName: checked ? "checkmark.square": "square")
.resizable()
.aspectRatio(contentMode: .fit)
.scaledToFit()
.foregroundColor(.black)
.frame(height: 20)
}
Text("I agree")
.fontWeight(.bold)
Spacer()
}
.padding(.horizontal, 20)
}
}
但是,我希望它工作:
var checked:Bool = false
struct ContentView: View {
var body: some View {
HStack {
Button(action: {checked.toggle()}) {
Image(systemName: checked ? "checkmark.square": "square")
.resizable()
.aspectRatio(contentMode: .fit)
.scaledToFit()
.foregroundColor(.black)
.frame(height: 20)
}
Text("I agree")
.fontWeight(.bold)
Spacer()
}
.padding(.horizontal, 20)
}
}
【问题讨论】:
-
你会为此展示你的代码吗?
-
我确实分享了它。
标签: ios swift if-statement swiftui boolean