SwiftUI has two Alerts on a view, one of which is overridden

        It's like this. I recently wrote a page. After clicking two buttons, an Alert will appear to prompt the user. The second one was added recently. As a result, the code was submitted. The next day, my colleague said that the previous Alert was invalid. This is probably like this. The first Alert will not pop up after clicking it.
 

The code in question:

  @State private var showFirstAlert = false
  @State private var showSecondAlert = false

VStack{
         Button(action: {
          showFirstAlert = true
  }) {
      Text("alert111111")
  }

 Button(action: {
        showSecondAlert = true
  }) {
        Text("alert22222")
  }
}
 
.alert(isPresented: $showFirstAlert) {
    // This alert never shows
    Alert(title: Text("First Alert"), message: Text("This is the first alert"))
}
.alert(isPresented: $showSecondAlert) {
    // This alert does show
    Alert(title: Text("Second Alert"), message: Text("This is the second alert"))
}

Corrected code:

enum ActiveAlert {
    case first, second
}
struct ContentView: View {
    @State private var showAlert = false
    @State private var activeAlert: ActiveAlert = .first
    var body: some View {
            Button(action: {
          self.activeAlert = .first
          showAlert = true
  }) {
      Text("alert111111")
  }

   Button(action: {
            self.activeAlert = . second
            showAlert = true
    }) {
            Text("alert22222")
    }.alert(isPresented: $showAlert) {
           switch activeAlert {
             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"))
            }
        }
    }
}

Guess you like

Origin blog.csdn.net/qq_24459277/article/details/130860297