【问题标题】:SwiftUI Multiple alerts for same button [duplicate]SwiftUI同一按钮的多个警报[重复]
【发布时间】:2020-07-04 22:06:42
【问题描述】:

以下代码仅显示错误警报。有没有办法让警报匹配 IF 条件?

@State var showTrueAlert = false
@State var showFalseAlert = false

var body: some View {
    Button(action: {
        let isTrue = Bool.random()
        if isTrue {
            self.showTrueAlert = true
            print("True Alert")
        } else {
            self.showFalseAlert = true
            print("False Alert")
        }
    }) {
        Text("Random Alert")
            .font(.largeTitle)
    }
    .alert(isPresented: $showTrueAlert) {
        Alert(title: Text("True"))
    }
    .alert(isPresented: $showFalseAlert) {
        Alert(title: Text("False"))
    }
}

【问题讨论】:

标签: swiftui


【解决方案1】:

您只能将.alert 应用于视图一次。创建一个仅处理警报当前状态的状态,然后创建两个变量来决定是否按下了假或真。 (也可能只将其存储在一个变量中)

struct ContentView6: View {

    @State var showAlert : Bool  = false
    
    @State var showTrueAlert = false
    @State var showFalseAlert = false

    var body: some View {
        Button(action: {
            let isTrue = Bool.random()
            if isTrue
            {
                self.showTrueAlert = true
                self.showAlert = true
                print("True Alert")
            } else {
                self.showFalseAlert = true
                self.showAlert = true
                print("False Alert")
            }
        }) {
            
            Text("Random Alert")
                .font(.largeTitle)
        }
        .alert(isPresented: Binding<Bool>(
            get: {
                self.showAlert
            },
            set: {
                self.showAlert = $0
                self.showTrueAlert = false
                self.showFalseAlert = false
            })) {
            if (showTrueAlert)
            {
                return Alert(title: Text("True"))
            }
            else
            {
                return Alert(title: Text("False"))
            }
          }
      }
}

【讨论】:

    猜你喜欢
    • 2021-04-02
    • 1970-01-01
    • 2021-08-02
    • 2020-04-01
    • 2021-04-08
    • 2019-09-02
    • 2022-06-15
    • 2021-07-19
    • 2023-04-07
    相关资源
    最近更新 更多