如何在 SwiftUI 的一个视图上有两个警报? [英] How can I have two alerts on one view in SwiftUI?

查看:19
本文介绍了如何在 SwiftUI 的一个视图上有两个警报?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望将两个独特的警报附加到同一个 Button 视图.当我使用下面的代码时,只有底部的警报有效.

I want to have two unique alerts attached to the same Button view. When I use the code below, only the alert on the bottom works.

我在 macOS Catalina 上使用官方发布的 Xcode 11.

I'm using the official release of Xcode 11 on macOS Catalina.

@State private var showFirstAlert = false
@State private var showSecondAlert = false

Button(action: {
    if Bool.random() {
        showFirstAlert = true
    } else {
        showSecondAlert = true
    }
}) {
    Text("Show random alert")
}
.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"))
}

当我将 showFirstAlert 设置为 true 时,我希望显示第一个警报,而当我将 showSecondAlert 设置为 true 时,我希望显示第二个警报.只有第二个警报显示其状态何时为真,但第一个警报什么都不做.

I expect first alert to show when I set showFirstAlert to true and I expect the second alert to show when I set showSecondAlert to true. Only the second alert shows when its state is true but the first one does nothing.

推荐答案

.alert(isPresented) 的第二次调用将覆盖第一次调用.你真正想要的是一个 Binding 来表示是否出现警报,以及一些设置,哪些警报应该从 .alert(isPresented) 之后的闭包中返回.您可以为此使用 Bool,但我继续使用枚举来完成它,因为它可以扩展到两个以上的警报.

The second call to .alert(isPresented) is overriding the first. What you really want is one Binding<Bool> to denote whether the alert is presented, and some setting for which alert should be returned from the closure following .alert(isPresented). You could use a Bool for this, but I went ahead and did it with an enum, as that scales to more than two alerts.

enum ActiveAlert {
    case first, second
}

struct ToggleView: View {
    @State private var showAlert = false
    @State private var activeAlert: ActiveAlert = .first

    var body: some View {

        Button(action: {
            if Bool.random() {
                self.activeAlert = .first
            } else {
                self.activeAlert = .second
            }
            self.showAlert = true
        }) {
            Text("Show random alert")
        }
        .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"))
            }
        }
    }
}

这篇关于如何在 SwiftUI 的一个视图上有两个警报?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆