How can I have two alerts on one view in SwiftUI?

前端 未结 4 1454
闹比i
闹比i 2020-12-10 03:02

I want to have two unique alerts attached to the same Button view. When I use the code below, only the alert on the bottom works.

I\'m using the officia

4条回答
  •  时光说笑
    2020-12-10 03:44

    I improved a litle Ben's answer. You can show multiple alerts dynamically by using .alert(item:) instead .alert(isPresented:):

    struct AlertItem: Identifiable {
        var id = UUID()
        var title: Text
        var message: Text?
        var dismissButton: Alert.Button?
    }
    
    struct ContentView: View {
    
        @State private var alertItem: AlertItem?
    
        var body: some View {
            VStack {
                Button("First Alert") {
                    self.alertItem = AlertItem(title: Text("First Alert"), message: Text("Message"))
                }
                Button("Second Alert") {
                    self.alertItem = AlertItem(title: Text("Second Alert"), message: nil, dismissButton: .cancel(Text("Some Cancel")))
                }
                Button("Third Alert") {
                    self.alertItem = AlertItem(title: Text("Third Alert"))
                }
            }
            .alert(item: $alertItem) { alertItem in
                Alert(title: alertItem.title, message: alertItem.message, dismissButton: alertItem.dismissButton)
            }
        }
    }
    

提交回复
热议问题