OS X storyboard: how to show a window programmatically?

邮差的信 提交于 2019-11-30 21:34:42

This is how you have to do to show your Windows programmatically:

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()
    }
}

or you can create an optional NSWindow var to store your window before you close it as follow

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)
        }
    }
}

The makeKeyAndOrderFront method is a NSWindow method, but instantiateInitialController returns the window controller, not its window.

Also, if the window is hidden on deactivate, you wouldn't want to instantiate another copy. Keep a reference to the window and re-show that.

Finally, you may need to bring the app to the front too. Call [NSApp activateIgnoringOtherApps:YES] (or the Swift equivalent).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!