没有Storyboard,NSApplicationDelegate无法正常工作 [英] NSApplicationDelegate not working without Storyboard
问题描述
我正在尝试在macOS Sierra上的Xcode 8(稳定版)中创建没有情节提要的macOS应用程序.但是,我的AppDelegate
甚至没有被启动.这是我的代码:
I'm attempting to create a macOS application without a storyboard in Xcode 8 (stable) on macOS Sierra. However, my AppDelegate
is not even being initiated. Here's the code I have:
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)
}
}
init
或applicationDidFinishLaunching(_ aNotification: Notification)
都没有被调用.任何帮助将不胜感激.
Neither init
or applicationDidFinishLaunching(_ aNotification: Notification)
is being called. Any help would be much appreciated.
推荐答案
您需要在此处做一些事情
You need to do a few things here
- 从plist删除
NSMainStoryboardFile
键/值 - 创建一个
NSApplication
子类并将其分配给Principal Class (NSPrincipalClass)
键.
- Delete
NSMainStoryboardFile
key/value from the plist - Create a
NSApplication
subclass and assign it to thePrincipal Class (NSPrincipalClass)
key.
该名称必须与您的模块名称完全匹配.
The name must be fully qualified with your module name.
- 在NSApplication子类中手动实例化您的委托,并将其分配给
delegate
属性.
- Manually instantiate your delegate in your NSApplication subclass and assign it to the
delegate
property.
确保对您的委托对象保持强烈的引用.香港专业教育学院只是在这里使用let
.
Make sure you keep a strong reference to your delegate object. Ive just used a let
here.
class GrookApplication: NSApplication {
let strongDelegate = AppDelegate()
override init() {
super.init()
self.delegate = strongDelegate
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
例如一个简单的委托人.
e.g a simple 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 (已验证高塞拉山脉)
EDIT 2018 Verified High Sierra
不要不要尝试在init
内执行窗口或视图控制器初始化,这将导致双重应用初始化问题并崩溃.该应用程序在此阶段尚未完成启动.等到applicationDidFinishLaunching
触发所有重要操作.
Do NOT try and do window or view controller initialisation inside init
this leads to double app initialisation issues and crashing. The app has not finished launching at this stage. Wait until applicationDidFinishLaunching
to fire any significant operations.
这篇关于没有Storyboard,NSApplicationDelegate无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!