我正在制作一个简单的菜单栏应用程序,其中包含2个项目-首选项和退出
当我单击首选项
时,我想打开一个新窗口目前我有
func applicationDidFinishLaunching(_ aNotification: Notification) {
constructMenu()
}
func constructMenu() {
let menu = NSMenu()
menu.addItem(NSMenuItem(
title: "Preferences...",
action: #selector(AppDelegate.preferencesWindow(_:)),
keyEquivalent: "P"))
menu.addItem(NSMenuItem.separator())
menu.addItem(NSMenuItem(
title: "Quit",
action: #selector(NSApplication.terminate(_:)),
keyEquivalent: "q"))
statusItem.menu = menu
}
@objc func preferencesWindow(_ sender: Any) {
print("open preference window here")
if let storyboard = NSStoryboard(name: NSStoryboard.Name(rawValue: "Main"), bundle: nil) {
let controller = storyboard.instantiateControllerWithIdentifier("preferencesWindow")
as NSViewController
if let window = NSApplication.shared.mainWindow {
window.contentViewController = controller // just swap
}
}
}
但是它会在这行上引发错误
如果让Storyboard = NSStoryboard(name:NSStoryboard.Name(rawValue:“ Main”),bundle:nil){
状态
用于条件绑定的初始化程序必须具有可选类型,而不是“ NSStoryboard”
当我单击首选项时,会记录 print 语句,但是我不知道如何以编程方式打开Window。
我刚刚从对象库中拖动了 Window Controller ,并为 StoryBoard ID 指定了 preferencesWindow >
由于上述错误,我也尝试了以下方法
@objc func preferencesWindow(_ sender: Any) {
print("open preference window here")
let storyboard = NSStoryboard(name: NSStoryboard.Name(rawValue: "Main"), bundle: nil)
let controller = storyboard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier(rawValue: "preferencesWindow")) as! NSViewController
if let window = NSApplication.shared.mainWindow {
window.contentViewController = controller // just swap
}
}
,但它仅记录日志且从不打开窗口。我该怎么办?
答案 0 :(得分:1)
当我在SO上发布问题时,我会很快找到答案。这是对我有用的东西
@objc func preferencesWindow(_ sender: Any) {
var myWindow: NSWindow? = nil
let storyboard = NSStoryboard(name: NSStoryboard.Name(rawValue: "Main"),bundle: nil)
let controller = storyboard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier(rawValue: "preferencesWindow")) as! NSViewController
myWindow = NSWindow(contentViewController: controller)
NSApp.activate(ignoringOtherApps: true)
myWindow?.makeKeyAndOrderFront(self)
let vc = NSWindowController(window: myWindow)
vc.showWindow(self)
}