【问题标题】:Open and bring new window to front when pressing NSMenuItem按下 NSMenuItem 时打开并将新窗口置于最前面
【发布时间】:2021-02-20 18:33:04
【问题描述】:

我有一个作为代理 (LSUIElement) 运行的 macOS 菜单应用程序。

我需要它有一个配套设置窗口。 NSMenu中有一个“设置”NSMenuItem,要求是打开一个实际的窗口,按下时把它带到最前面。

窗口是 SwiftUI 驱动的。以下是它的工作原理:

// main is an NSMenu
        main.addItem(
            withTitle: "Settings",
            action: #selector(AppDelegate.openSettings),
            keyEquivalent: "")
    @objc func openSettings() {
        let detailView = SettingsWindow(); // Swift UI view
        let controller = DetailWindowController(rootView: detailView) // See below
        controller.window?.title = "Settings";
        controller.showWindow(nil)
        NSApp.activate(ignoringOtherApps: true)
    }
class DetailWindowController<RootView : View>: NSWindowController {
    convenience init(rootView: RootView) {
        let hostingController = NSHostingController(rootView: rootView.frame(width: 400, height: 500))
        let window = NSWindow(contentViewController: hostingController)
        window.setContentSize(NSSize(width: 400, height: 500))
        self.init(window: window)
    }
}

实际发生的情况

当前行为是窗口打开,但它始终位于当前处于前台的其他窗口之后。

我需要它在前台。

上面代码中的NSApp.activate(ignoringOtherApps: true) 试图实现这一点,但没有奏效。

任何帮助都会令人惊叹。非常感谢。

【问题讨论】:

    标签: macos nsmenu


    【解决方案1】:

    最后想通了。我需要这 3 个。应该更好地管理激活策略,但它的价值在于它的工作原理。

    NSApp.setActivationPolicy(.regular)
    NSApp.activate(ignoringOtherApps: true)
    settingsWindow!.window?.orderFrontRegardless()
    

    上下文

    @objc func openSettings() {
        if(settingsWindow == nil) {
            let detailView = ActionWindow();
            settingsWindow = DetailWindowController(rootView: detailView)
            settingsWindow!.window?.title = "Cloud Brains - Settings";
            settingsWindow!.showWindow(nil)
        }
        NSApp.setActivationPolicy(.regular)
        NSApp.activate(ignoringOtherApps: true)
        settingsWindow!.window?.orderFrontRegardless()
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-20
      • 1970-01-01
      • 2010-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多