SwiftUI的一个视图上有两个Alert,其中一个被覆盖
2021-09-08 本文已影响0人
纵横四海
我想将两个唯一的警报附加到同一Button视图。当我使用下面的代码时,只有底部的警报起作用。
是这样的,最近写了一个页面,有两个按钮点击之后都会出现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"))
}
}
}
}