gpt4 book ai didi

swift - cocoa Xcode : Open Window Controller from AppDelegate Programmatically using Swift 4 for Mac?

转载 作者:行者123 更新时间:2023-11-28 05:53:38 24 4
gpt4 key购买 nike

我正在制作一个简单的菜单栏应用,它有 2 个项目 - PreferencesQuit

我想在单击首选项时打开一个新窗口

目前我有

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) {

说明

Initializer for conditional binding must have Optional type, not 'NSStoryboard'

当我单击Preferences 时,print 语句会被记录下来,但我不知道如何以编程方式打开窗口。

我刚刚从 Object Library 中拖出 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
}
}

但它只记录并且从不打开窗口。我该怎么办?

最佳答案

当我在 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)
}

关于swift - cocoa Xcode : Open Window Controller from AppDelegate Programmatically using Swift 4 for Mac?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52052562/

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