如何使用 SwiftUI 连续呈现两个警报视图 [英] How to consecutively present two alert views using SwiftUI
问题描述
我想在点击第一个警报视图的关闭按钮后立即显示第二个警报视图.
I want to immediately present the second alert view after click the dismiss button of the first alert view.
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")))}
})
)
但是,它给了我一个错误:Alert.Button"不能转换为Alert.Button?"如果我将此段置于dismissButton 的范围之外,它将覆盖之前的.alert.那么我该怎么做,我只想在单击第一个警报的关闭按钮后弹出第二个警报.谢谢.
However, it gives me an error of 'Alert.Button' is not convertible to 'Alert.Button?' If I put this segment out of the scope of dismissButton, it will override the previous .alert. So how can i do it, I just want to pop up the second alert after clicking the dismiss button of the first alert. Thanks.
推荐答案
出现(使用 Xcode 11.2 测试):
It appears (tested with Xcode 11.2):
- 虽然没有记录,但不允许添加多个.alert 修饰符在一个视图构建器序列中 - 仅适用于最新
- 不允许向EmptyView添加.alert修饰符,它不起作用完全
我找到了@Rohit 提出的替代解决方案.在某些情况下,有很多警报,这可能会导致代码更简单.
I've found alternate solution to proposed by @Rohit. In some situations, many alerts, this might result in simpler code.
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()
}
}
这篇关于如何使用 SwiftUI 连续呈现两个警报视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!