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

前端 未结 4 1466
闹比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:33

    There's a variation on this solution which only uses one state variable rather than two. It uses the fact that there is another .alert() form which takes an Identifiable item rather than a Bool, so extra information can be passed in that:

    struct AlertIdentifier: Identifiable {
        enum Choice {
            case first, second
        }
    
        var id: Choice
    }
    
    struct ContentView: View {
        @State private var alertIdentifier: AlertIdentifier?
    
        var body: some View {
            HStack {
                Button("Show First Alert") {
                    self.alertIdentifier = AlertIdentifier(id: .first)
                }
                Button("Show Second Alert") {
                    self.alertIdentifier = AlertIdentifier(id: .second)
                }
            }
            .alert(item: $alertIdentifier) { alert in
                switch alert.id {
                case .first:
                    return Alert(title: Text("First Alert"),
                                 message: Text("This is the first alert"))
                case .second:
                    return Alert(title: Text("Second Alert"),
                                 message: Text("This is the second alert"))
                }
            }
        }
    }
    

提交回复
热议问题