简体   繁体   English

如何使用 SwiftUI 在 MacOS 上显示警报对话框

[英]How to display Alert dialog on MacOS using SwiftUI

How can I display an alert dialog box from a menu item for MacOS apps using SwiftUI ?如何使用SwiftUI从 MacOS 应用程序的菜单项中显示警告对话框? The usual code which works for iOS @State var isOn = false and .alert("title", isPresented: isOn) {..} doesn't work.适用于 iOS @State var isOn = false.alert("title", isPresented: isOn) {..}的常用代码不起作用。

@main
struct MyApp: App {

var body: some Scene {
    WindowGroup {
        ContentView()
    }.commands {
        CommandMenu("Test menu") {
            Button(action: {
                // I want to show an alert dialog dialog here.
            }) {
                Text("Click Me")
            }
        }
    }
}

The usual code works fine.通常的代码工作正常。 You would never try to stuff an Alert inside of a Button .您永远不会尝试在Button中填充Alert You wouldn't do it here.你不会在这里做的。

@main
struct MyApp: App {

    @State var isOn = false
    
    var body: some Scene {
        WindowGroup {
            NavigationView {
                ContentView()
                    .alert("title", isPresented: $isOn) {
                        Button("OK", role: .cancel) { }
                    }
            }
        }.commands {
            CommandMenu("Test menu") {
                Button(action: {
                    isOn = true
                }) {
                    Text("Click Me")
                }
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在UIWebView中使用stringByEvaluatingJavaScriptFromString而不是Swift中的performSelectorOnMainThread显示JavaScript警报对话框? - How to display a JavaScript alert dialog in UIWebView using stringByEvaluatingJavaScriptFromString but not performSelectorOnMainThread in Swift? 在 MacOS 中使用 NSSharingServicePicker 的 SwiftUI - SwiftUI using NSSharingServicePicker in MacOS SwiftUI:在 MacOS 上使用 enterFullScreenMode - SwiftUI: Using enterFullScreenMode on MacOS 使用SwiftUI在条件内显示警报 - Display an Alert inside a conditional with SwiftUI SwiftUI 显示警报的问题 – 不会显示警报框 - Issue with SwiftUI displaying Alert – Will not display alert box SwiftUI:如何在第一次启动时显示警报 - SwiftUI: How can I display an alert on the very first start 如何使用 SwiftUI 显示警报 - How to present an Alert with SwiftUI iOS 15:如何在 SwiftUI 中启动应用程序时显示 ATT 对话框 - iOS 15: How to display ATT dialog when the app starts in SwiftUI 如何在 SwiftUI 应用程序中使用 NSViewRepresentable 在 macOS 上使用 CAEmitterLayer - How to use CAEmitterLayer on macOS in a SwiftUI app using NSViewRepresentable 如何在 MacOS 上使用 SwiftUI 从菜单栏弹出窗口打开窗口 - How to open a window from a menu bar popover using SwiftUI on MacOS
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM