当前位置 : 主页 > 手机开发 > 其它 >

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

来源:互联网 收集:自由互联 发布时间:2021-06-11
我正在创建一个OS X状态栏应用程序. 我想要实现以下目标: 应用程序启动不可见,菜单栏项 点击菜单栏项目显示主窗口 在停用时,窗口被隐藏 因此,我尝试以编程方式显示单击菜单项时的
我正在创建一个OS X状态栏应用程序.

我想要实现以下目标:

>应用程序启动不可见,菜单栏项
>点击菜单栏项目显示主窗口
>在停用时,窗口被隐藏

因此,我尝试以编程方式显示单击菜单项时的主窗口,但没有成功.

我的主窗口已选中“隐藏停用时”.隐藏后,我无法使用代码再次显示它.

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

@IBAction func menuClick(sender: AnyObject) {
    var mainWindow = NSStoryboard(name: "Main", bundle: nil)?.instantiateInitialController()
    mainWindow?.makeKeyAndOrderFront(self)
}
这是您以编程方式显示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)
        }
    }
}
网友评论