FPL*_*FPL 4 ios property-binding swift computed-properties swiftui
我正在尝试根据计算属性在 Swift 中显示警报。基本上,每当用户单击按钮时,“round”的值就会更新。当进行超过 10 轮时,会显示警报。
为此,我创建了一个名为“showingAlert”的布尔变量。这必须是一个 @State var,以便当用户关闭警报时它会再次设置为 false。
但是,编译器告诉我像 @State 这样的属性包装器“不能应用于计算属性”:-(
这是我尝试过的代码:
@State var round = 0
@State var showingAlert:Bool {round > 10 ? true : false}
func result(player: Int, app: Int) {
if player > app {
round += 1
}
else {
round += 1
}
}
var body: some View {
Button(action: {self.result(player: 1, app: 1)}) {
Text("Button")
}
.alert(isPresented: $showingAlert) {
Alert(title: Text("title"), message: Text("message"), dismissButton: .default(Text("Continue"))
)
}
Run Code Online (Sandbox Code Playgroud)
有什么办法解决这个问题吗?我很想创建一个不显示错误消息的警报。
您可以简单地使用Binding.constant(_:)。将计算属性转换为绑定属性。
@State var round = 0
var showingAlert:Bool {round > 10 ? true : false}
func result(player: Int, app: Int) {
if player > app {
round += 1
}
else {
round += 1
}
}
var body: some View {
Button(action: {self.result(player: 1, app: 1)}) {
Text("Button")
}
.alert(isPresented: .constant(showingAlert)) {
Alert(title: Text("title"), message: Text("message"), dismissButton: .default(Text("Continue"))
)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3670 次 |
| 最近记录: |