gpt4 book ai didi

swift - 没有 Storyboard ,NSApplicationDelegate 无法工作

转载 作者:IT王子 更新时间:2023-10-29 05:23:04 25 4
gpt4 key购买 nike

我正在尝试在 macOS Sierra 上的 Xcode 8(稳定版)中创建一个没有 Storyboard的 macOS 应用程序。但是,我的 AppDelegate 甚至没有启动。这是我的代码:

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
var window: NSWindow!

override init() {
super.init()
print("Init")
}

func applicationDidFinishLaunching(_ aNotification: Notification) {
print("Finished launching")

// Create a window
window = NSWindow()

// Add the view controller
let viewController = ViewController()
window.contentView?.addSubview(viewController.view)

// Show the window
window.makeKeyAndOrderFront(nil)
}
}

initapplicationDidFinishLaunching(_ aNotification: Notification) 均未被调用。任何帮助将不胜感激。

最佳答案

这里需要做一些事情

  1. 从 plist 中删除 NSMainStoryboardFile 键/值
  2. 创建一个 NSApplication 子类并将其分配给 Principal Class (NSPrincipalClass) 键。

assign custom class to principal class

名称必须完全符合您的模块名称。

  1. 在 NSApplication 子类中手动实例化您的委托(delegate)并将其分配给 delegate 属性。

确保您保持对委托(delegate)对象的强引用。我刚刚在这里使用了 let

class GrookApplication: NSApplication {

let strongDelegate = AppDelegate()

override init() {
super.init()
self.delegate = strongDelegate
}

required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}

}

例如一个简单的委托(delegate)。

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

override init() {
super.init()
print("wassup")
//conceptual proof of life init override
//wait until applicationDidFinishLaunching , specially for UI
}

var window: NSWindow!
func applicationDidFinishLaunching(_ aNotification: Notification) {
print("yo! I'm alive")
window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 200, height: 200), styleMask: .titled, backing: .buffered, defer: false)
window.makeKeyAndOrderFront(nil)
}

}

EDIT 2018 已验证 High Sierra

不要尝试在 init 中进行窗口或 View Controller 初始化,这会导致双重应用程序初始化问题和崩溃。该应用程序在此阶段尚未完成启动。等到 applicationDidFinishLaunching 触发任何重要操作。

关于swift - 没有 Storyboard ,NSApplicationDelegate 无法工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40008141/

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