SwiftUI的一個(gè)視圖上有兩個(gè)Alert,其中一個(gè)被覆蓋

我想將兩個(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"))
            }
        }
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容