【发布时间】:2018-08-28 07:42:19
【问题描述】:
我正在制作一个简单的菜单栏应用程序,它有 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
}
}
}
但它会在这一行引发错误
if let storyboard = NSStoryboard(name: NSStoryboard.Name(rawValue: "Main"), bundle: nil) {
陈述
条件绑定的初始化器必须是 Optional 类型,而不是 'NSStoryboard'
当我单击 Preferences 时,print 语句会被记录,但我不知道如何以编程方式打开 Window。
我刚刚从 Object Library 中拖出 Window Controller 并给 StoryBoard ID 一个 preferencesWindow 值 p>
由于上述错误,我也尝试了以下方法
@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
}
}
但它只记录并且从不打开窗口。我该怎么办?
【问题讨论】:
标签: swift xcode macos cocoa swift4