我正在制作一个简单的菜单栏应用程序,其中包含2项- Preferences和Quit
当我单击Preferences时,我想打开一个新窗口
目前我有
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
}
}
}但它会在这一行抛出错误。
如果让情节提要=NSStoryboard(名称: NSStoryboard.Name(rawValue:"Main"),bundle: nil) {
陈述
条件绑定的初始化程序必须具有可选类型,而不是“NSStoryboard”
当我单击Preferences时,打印语句会被记录下来,但我不知道如何编程打开窗口。
我刚刚从preferencesWindow对象库中拖动了窗口控制器&给StoryBoard ID一个值
由于上述错误,我还尝试了以下操作
@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
}
}但它只是日志&从来没有打开过窗户。我该怎么办?
发布于 2018-08-28 08:01:14
当我在上面发布一个问题时,我很快就会找到答案。以下是对我有用的东西
@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)
}https://stackoverflow.com/questions/52052562
复制相似问题