OS X故事板:如何以编程方式显示窗口? [英] OS X storyboard: how to show a window programmatically?
本文介绍了OS X故事板:如何以编程方式显示窗口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在创建OS X状态栏应用程序.
I am creating an OS X status bar application.
我正在努力实现以下目标:
I am trying to achieve the following:
- 应用程序开始不可见,带有菜单栏项
- 单击菜单栏项将显示主窗口
- 停用后,窗口被隐藏
因此,我试图在单击菜单项时以编程方式显示主窗口,但没有成功.
So I am trying to programmatically show the main window when the menu item is clicked, but with no success.
我的主窗口已选中隐藏停用" .隐藏后,我将无法使用代码再次使其可见.
My main window has "Hide on deactivate" checked. Once hidden, I cannot make it visible again using code.
这是我现在拥有的代码,但是它不起作用:
Here is the code I have for now, but it doesn't work:
@IBAction func menuClick(sender: AnyObject) {
var mainWindow = NSStoryboard(name: "Main", bundle: nil)?.instantiateInitialController()
mainWindow?.makeKeyAndOrderFront(self)
}
推荐答案
这是您以编程方式显示Windows的方法:
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()
}
}
或者您可以创建一个可选的NSWindow var来存储您的窗口,然后按照以下步骤关闭它
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)
}
}
}
这篇关于OS X故事板:如何以编程方式显示窗口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文