【问题标题】:SwiftUI multiple Alerts in one viewSwiftUI 多个警报在一个视图中
【发布时间】:2021-10-08 09:08:37
【问题描述】:

我在 1 个视图中有 2 个警报(这些警报确实单独工作),但是当将 2 个警报组合到 1 个视图中时,它只显示警报 2。

我已阅读您需要将这些附加到不同的视图。

因此,我已将 1 个警报附加到 button,并将 1 个警报附加到包含的 VStack。仍然只显示第二个警报。我试图让两个警报都起作用。

var body: some View {
     ScrollView {
         VStack (alignment: .leading) {
             ...some stuff
             VStack {
                 Button(action: {
                        dosomestuff
                        showingIntrestedAlert.toggle()
                    }) {
                        Text("Press Me")
                    }.alert(isPresented: $showingIntrestedAlert) {
                        Alert(title: Text("alert1"), message: Text("showing alert 1"), dismissButton: .default(Text("OK")))
                    }
             }
          }
          .alert(isPresented: $fromViewModel.alreadyLikedUser) {
            Alert(title: Text("alert2"), message: Text("alert 2 shown"), dismissButton: .default(Text("OK")))
        }
      }
 }

【问题讨论】:

标签: swift swiftui


【解决方案1】:

您可以通过以下方式插入多条警报消息。

首先:为您想要处理的每个警报声明变量。

struct xyz : View 
{
    @State private var myFirstAlert : Bool = false
    @State private var mySecondAlert : Bool = false
 ....
}

在你的身体里写下你的按钮内容......

var body: some View {
    VStack{
        Text("Hello World")
        Spacer()
        ....
        Button {
            guard someThingIsEmpty else{
                myFirstAlert = true
                return
            }
            guard somethingIsWrong else {
                mySecondAlert = true
                return
            }
            //Button stuff
        } label: { ZStack {Text("Bla"),....}} .alert(isPresented: self.$myFirstAlert){
         Alert(title: Text("Something went wrong!"))}
    .alert(isPresented: self.$mySecondAlert){
    Alert(title: Text("That was shitty"), message: Text("Something went totally wrong"), dismissButton: .default(Text("Urghs"), action: {}}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-23
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    • 1970-01-01
    • 2020-06-21
    • 1970-01-01
    相关资源
    最近更新 更多