我想將兩個(gè)唯一的警報(bào)附加到同一Button視圖。當(dāng)我使用下面的代碼時(shí),只有底部的警報(bào)起作用。
是這樣的,最近寫了一個(gè)頁(yè)面,有兩個(gè)按鈕點(diǎn)擊之后都會(huì)出現(xiàn)Alert來(lái)提示用戶,第二個(gè)是最近加的,結(jié)果提交了Code,第二天同事說(shuō)之前的Alert失效了。大概就是這樣子,第一個(gè)Alert點(diǎn)擊之后不會(huì)彈出來(lái)了
@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"))
}
}
}
}