下面的代码仅显示错误警报。有没有办法使警报与IF条件匹配?
@State var showTrueAlert = false
@State var showFalseAlert = false
var body: some View {
Button(action: {
let isTrue = Bool.random()
if isTrue {
self.showTrueAlert = true
print("True Alert")
} else {
self.showFalseAlert = true
print("False Alert")
}
}) {
Text("Random Alert")
.font(.largeTitle)
}
.alert(isPresented: $showTrueAlert) {
Alert(title: Text("True"))
}
.alert(isPresented: $showFalseAlert) {
Alert(title: Text("False"))
}
}
答案 0 :(得分:1)
您只能将.alert
应用于视图一次。创建一个仅处理警报当前状态的状态,然后创建两个变量,确定是否按下了false或true。 (也可能只将其存储在一个变量中)
struct ContentView6: View {
@State var showAlert : Bool = false
@State var showTrueAlert = false
@State var showFalseAlert = false
var body: some View {
Button(action: {
let isTrue = Bool.random()
if isTrue
{
self.showTrueAlert = true
self.showAlert = true
print("True Alert")
} else {
self.showFalseAlert = true
self.showAlert = true
print("False Alert")
}
}) {
Text("Random Alert")
.font(.largeTitle)
}
.alert(isPresented: Binding<Bool>(
get: {
self.showAlert
},
set: {
self.showAlert = $0
self.showTrueAlert = false
self.showFalseAlert = false
})) {
if (showTrueAlert)
{
return Alert(title: Text("True"))
}
else
{
return Alert(title: Text("False"))
}
}
}
}