【问题标题】:Show NSWindowController from StatusMenu从 StatusMenu 显示 NSWindowController
【发布时间】:2017-12-11 14:50:39
【问题描述】:

我有一个通过状态菜单中的扩展程序运行的应用程序。

我有一个“设置”按钮,当用户点击它时应该启动我的故事板的特定视图。

我尝试了很多不同的方法,Open NSWindowController from NSMenuCocoa - How to bring particular window to come in foreground from StatusMenu

这是我当前的代码:

StatusMenu.swift

func showSettings() {

  var mainWindowController = MainWindowController()
  mainWindowController.showWindow(nil)

}

MainWindowController.swift

class MainWindowController: NSWindowController {

 override func windowDidLoad() {
   super.windowDidLoad()

   self.window?.center()
   self.window?.makeKeyAndOrderFront(nil)
   NSApp.activate(ignoringOtherApps: true)

   }

}

【问题讨论】:

  • 将 mainWindowController 声明移出 showSettings 方法
  • @LeoDabus 只有第一行?它不起作用...
  • 你确定 window 属性不是 nil 吗?
  • @LeoDabus 是的...是因为我在故事板中调用了特定的 NSWindowController 吗?我看到其他一些需要 windowNibName 函数的解决方案

标签: ios swift macos cocoa nswindowcontroller


【解决方案1】:

发布的代码有 2 个潜在问题:

  1. MainWindowController.init 不是由NSWindowController 实现的,而是由NSObject 实现的,这意味着与 NSViewControllers 不同,它查找同名的 Nib 文件。使用这个:

    extension MainWindowController {
        convenience init() {
            self.init(windowNibName: .init(rawValue: "MainWindowController"))
        }
    }
    
  2. 生成的实例是从mainWindowController 引用的,但这个变量只有showSettings() 的局部范围。这意味着,一旦showSettings() 完成,垃圾收集器将再次释放该对象。它就像从未存储过一样好。您需要在存在的对象中或作为全局变量保留永久引用,如下所示:

     // Assuming your StatusMenu instance is strongly referenced for the whole runtime
     class StatusMenu {
         var mainWindowController: MainWindowController?
         func showSettings() {
            self.mainWindowController = MainWindowController()
            self.mainWindowController?.showWindow(nil)
         }
     }
    

【讨论】:

  • 我正在尝试实施您的解决方案,但我无法使用“.init”...是 Swift 4 吗?
  • 是的,在这种情况下它是NSNib.Name(rawValue:) 的缩写;在 Swift 3 中,你应该可以直接传递字符串。
  • 好的,谢谢,我刚刚尝试过,但出现错误:“无法加载窗口笔尖文件“MainWindowController”,是我的笔尖在我的故事板中的问题吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-07-03
  • 2015-02-01
  • 2019-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多