如何使用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")))}
})
)

但是,它给我一个错误消息,“ Alert.Button”不能转换为“ Alert.Button?”。 如果将此段放在dismissButton的范围之外,它将覆盖以前的.alert。 因此,我该怎么做,我只想在单击第一个警报的关闭按钮后弹出第二个警报。 谢谢。

maomaoaijie 回答:如何使用SwiftUI连续显示两个警报视图

请尝试以下代码。

使用SwiftUI连续显示两个警报视图

struct ContentView: View {

    @State var showAlert: Bool = false
    @State var alertIsVisible: Bool = false
    @State var bonusAlertIsVisible: Bool = false

    var body: some View {

        NavigationView {

            Button(action: {
                self.displayAlert()
            }) {
                Text("Hit Me!")
            }
            .alert(isPresented: $showAlert) { () -> Alert in
                if alertIsVisible {
                    return Alert(title: Text("First alert"),message: Text("\n"),dismissButton:.default(Text("Next Round"),action: {
                        DispatchQueue.main.async {
                            self.displayAlert()
                        }
                     })
                   )
                }
                else {
                    return Alert(title: Text("Bonus"),message: Text("You've earned 100 points bonus!!"),dismissButton:.default(Text("Close"),action: {
                                self.showAlert = false
                                self.bonusAlertIsVisible = false
                                self.alertIsVisible = false
                        })
                    )
                }
            }
            .navigationBarTitle(Text("Alert"))
        }
    }

    func displayAlert() {

       self.showAlert = true
       if self.alertIsVisible == false {
            self.alertIsVisible = true
            self.bonusAlertIsVisible = false
       }
       else {
            self.alertIsVisible = false
            self.bonusAlertIsVisible = true
       }
    }
}
,

它出现了(经过Xcode 11.2测试):

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

我找到了@Rohit提出的替代解决方案。在某些情况下,很多警报可能会导致代码更简单。

ORDER BY
本文链接:https://www.f2er.com/3111233.html

大家都在问