我正在创建一个 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)
}
}
}
关于macos - OS X Storyboard : how to show a window programmatically?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27999114/