-1

The code below only shows the false alert. Is there a way to make the alert match the IF condition?

@State var showTrueAlert = false
@State var showFalseAlert = false

var body: some View {
    Button(action: {
        let isTrue = Bool.random()
        if isTrue {
            self.showTrueAlert = true
            print("True Alert")
        } else {
            self.showFalseAlert = true
            print("False Alert")
        }
    }) {
        Text("Random Alert")
            .font(.largeTitle)
    }
    .alert(isPresented: $showTrueAlert) {
        Alert(title: Text("True"))
    }
    .alert(isPresented: $showFalseAlert) {
        Alert(title: Text("False"))
    }
}
jtbandes
  • 115,675
  • 35
  • 233
  • 266
luis
  • 107
  • 1
  • 8
  • Does this answer your question? [How can I have two alerts on one view in SwiftUI?](https://stackoverflow.com/questions/58069516/how-can-i-have-two-alerts-on-one-view-in-swiftui) – pawello2222 Jul 04 '20 at 22:14
  • Yes. These links are very usefull. Thanks – luis Jul 04 '20 at 23:20

1 Answers1

1

You can apply .alert only once to a View. Create a State which only handles the current State of the Alert and then two variables which decide if false or true was pressed. (might store that in one variable only aswell)

struct ContentView6: View {

    @State var showAlert : Bool  = false
    
    @State var showTrueAlert = false
    @State var showFalseAlert = false

    var body: some View {
        Button(action: {
            let isTrue = Bool.random()
            if isTrue
            {
                self.showTrueAlert = true
                self.showAlert = true
                print("True Alert")
            } else {
                self.showFalseAlert = true
                self.showAlert = true
                print("False Alert")
            }
        }) {
            
            Text("Random Alert")
                .font(.largeTitle)
        }
        .alert(isPresented: Binding<Bool>(
            get: {
                self.showAlert
            },
            set: {
                self.showAlert = $0
                self.showTrueAlert = false
                self.showFalseAlert = false
            })) {
            if (showTrueAlert)
            {
                return Alert(title: Text("True"))
            }
            else
            {
                return Alert(title: Text("False"))
            }
          }
      }
}
davidev
  • 7,694
  • 5
  • 21
  • 56