OS X故事板:如何以编程方式显示窗口?

时间:2015-01-17 11:45:23

标签: macos cocoa swift uistoryboard

我正在创建一个OS X状态栏应用程序。

我正在努力实现以下目标:

  • app使用菜单栏项
  • 启动隐身
  • 点击菜单栏项目显示主窗口
  • 停用时,窗口隐藏

所以我试图以编程方式显示单击菜单项时的主窗口,但没有成功。

我的主窗口已选中“取消激活时隐藏”。隐藏后,我无法使用代码再次显示它。

这是我现在的代码,但它不起作用:

@IBAction func menuClick(sender: AnyObject) {
    var mainWindow = NSStoryboard(name: "Main", bundle: nil)?.instantiateInitialController()
    mainWindow?.makeKeyAndOrderFront(self)
}

2 个答案:

答案 0 :(得分:1)

makeKeyAndOrderFront方法是NSWindow方法,但instantiateInitialController返回窗口控制器,而不是窗口。

此外,如果窗口在停用时隐藏,则您不希望实例化另一个副本。保持对窗口的引用并重新显示。

最后,您可能还需要将应用程序带到前面。调用[NSApp activateIgnoringOtherApps:YES](或等效的Swift)。

答案 1 :(得分:0)

这是您以编程方式显示Windows的方法:

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

     let mainWindow = NSWindow(contentRect: NSMakeRect(0, 0, NSScreen.mainScreen()!.frame.width/2, NSScreen.mainScreen()!.frame.height/2), styleMask: NSTitledWindowMask|NSResizableWindowMask|NSMiniaturizableWindowMask|NSClosableWindowMask, backing: NSBackingStoreType.Buffered, defer: false)

    func createNewWindow(){
        mainWindow.title = "Main Window"
        mainWindow.opaque = false
        mainWindow.center()
        mainWindow.hidesOnDeactivate = true
        mainWindow.movableByWindowBackground = true
        mainWindow.backgroundColor = NSColor(calibratedHue: 0, saturation: 0, brightness: 1, alpha: 1)
        mainWindow.makeKeyAndOrderFront(nil)
    }
    func applicationDidFinishLaunching(aNotification: NSNotification) {
        // lets get rid of the main window just closing it as soon as the app launches
        NSApplication.sharedApplication().windows.first!.close()
    }
    func applicationWillTerminate(aNotification: NSNotification) {
        // Insert code here to tear down your application
    }
    @IBAction func menuClick(sender: AnyObject) {
        createNewWindow()
    }
}

或者您可以创建一个可选的NSWindow var来存储您的窗口,然后关闭它,如下所示

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
    var defaultWindow:NSWindow?
    func applicationDidFinishLaunching(aNotification: NSNotification) {
        // lets get rid of the main window just closing it as soon as the app launches
        defaultWindow = NSApplication.sharedApplication().windows.first as? NSWindow
        if let defaultWindow = defaultWindow {
            defaultWindow.close()
        }
    }
    func applicationWillTerminate(aNotification: NSNotification) {
        // Insert code here to tear down your application
    }
    @IBAction func menuClick(sender: AnyObject) {
        if let defaultWindow = defaultWindow {
            defaultWindow.makeKeyAndOrderFront(nil)
        }
    }
}