gpt4 book ai didi

macos - OS X Storyboard : how to show a window programmatically?

转载 作者:搜寻专家 更新时间:2023-10-31 08:05:20 26 4
gpt4 key购买 nike

我正在创建一个 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com