首页 > 解决方案 > 如何在弹出框前发送警报?

问题描述

我正在编写一个菜单栏应用程序,其中只有一个弹出框,这是动作所在。目标是 MacOS 10.15 Catalina。

在弹出窗口中,我想显示一个警报。代码是这样的:

struct ContentView: View {
    @State private var confirm = false
    var body: some View {
        return VStack {
            Button("Reset Settings", action: {
                self.confirm = true
            })
            .alert(isPresented: $confirm) {
                Alert(
                    title: Text("Do you really want to?"),
                    message: Text("Do you want to talk about it?"),
                    primaryButton: .default(Text("Oh, yeah")) {
                        print("Well, if you insist …")
                    },
                    secondaryButton: .cancel()
                )
            }
        }
    }
}

警报效果很好,但它出现在弹出框的后面。

如何将警报放在弹出框前面?

标签: swiftmacosswiftuialertpopover

解决方案


我假设警报是在弹出框将显示在顶部的视图上声明的(我在您的代码中看不到弹出框,所以我不能确定)。如果是这种情况,那么您需要在弹出框本身中声明警报,而不是在其背后的视图中。

例子:

var body: some View {
    VStack {
        Button("Reset Settings", action: {
                self.confirm = true
            })
            .popover(isPresented: $popoverPresentation) {
                
                PopoverView()
                    .alert() // declare alert here, inside the popover,
                // or even inside the `PopoverView`
                
            }
            // .alert() dont declare your alert here, outside the popover
    }
}

推荐阅读