[英]Cocoa Xcode: Open Window Controller from AppDelegate Programmatically using Swift 4 for Mac?
我正在制作一個簡單的菜單欄應用程序,它有 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
}
}
}
但它在這一行拋出錯誤
if let storyboard = NSStoryboard(name: NSStoryboard.Name(rawValue: "Main"), bundle: nil) {
陳述
條件綁定的初始化程序必須具有 Optional 類型,而不是“NSStoryboard”
當我單擊首選項時,會記錄打印語句,但我不知道如何以編程方式打開 Window。
我剛剛從對象庫中拖出Window Controller 並為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
}
}
但它只記錄並且從不打開窗口。 我該怎么辦?
當我在 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)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.