单击第一个警报视图的关闭按钮后,我想立即显示第二个警报视图。
Button(action: {
self.alertIsVisible = true
}) {
Text("Hit Me!")
}
.alert(isPresented: $alertIsVisible) { () -> Alert in
return Alert(title: Text("\(title)"), message: Text("\n"), dismissButton:.default(Text("Next Round"), action: {
if self.score == 100 {
self.bonusAlertIsVisible = true
}
.alert(isPresented: $bonusAlertIsVisible) {
Alert(title: Text("Bonus"), message: Text("You've earned 100 points bonus!!"), dismissButton: .default(Text("Close")))}
})
)
Run Code Online (Sandbox Code Playgroud)
但是,它给了我一个错误“Alert.Button”不能转换为“Alert.Button?” 如果我将此段置于dismissButton 的范围之外,它将覆盖之前的.alert。那么我该怎么做,我只想在单击第一个警报的关闭按钮后弹出第二个警报。谢谢。
它出现(使用 Xcode 11.2 测试):
我找到了@Rohit 提出的替代解决方案。在某些情况下,有很多警报,这可能会导致代码更简单。
struct TestTwoAlerts: View {
@State var alertIsVisible = false
@State var bonusAlertIsVisible = false
var score = 100
var title = "First alert"
var body: some View {
VStack {
Button(action: {
self.alertIsVisible = true
}) {
Text("Hit Me!")
}
.alert(isPresented: $alertIsVisible) {
Alert(title: Text("\(title)"), message: Text("\n"), dismissButton:.default(Text("Next Round"), action: {
if self.score == 100 {
DispatchQueue.main.async { // !! This part important !!
self.bonusAlertIsVisible = true
}
}
}))
}
Text("")
.alert(isPresented: $bonusAlertIsVisible) {
Alert(title: Text("Bonus"), message: Text("You've earned 100 points bonus!!"), dismissButton: .default(Text("Close")))
}
}
}
}
struct TestTwoAlerts_Previews: PreviewProvider {
static var previews: some View {
TestTwoAlerts()
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1389 次 |
最近记录: |