如何使用 SwiftUI 连续呈现两个警报视图

DaW*_* Xu 2 ios swift swiftui

单击第一个警报视图的关闭按钮后,我想立即显示第二个警报视图。

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。那么我该怎么做,我只想在单击第一个警报的关闭按钮后弹出第二个警报。谢谢。

Asp*_*eri 7

它出现(使用 Xcode 11.2 测试):

  1. 虽然没有记录,但不允许在一个视图构建器序列中添加多个 .alert 修饰符 - 仅适用于最新
  2. 不允许将 .alert 修饰符添加到 EmptyView,它根本不起作用

我找到了@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)