SwiftUI的一个视图上有两个Alert,其中一个被覆盖

        是这样的,最近写了一个页面,有两个按钮点击之后都会出现Alert来提示用户,第二个是最近加的,结果提交了Code,第二天同事说之前的Alert失效了。大概就是这样子,第一个Alert点击之后不会弹出来了
 

有问题的代码:

  @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"))
}

修正后的代码:

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"))
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_24459277/article/details/130860297