NSApplicationDelegate not working without Storyboard

前端 未结 3 1106
北恋
北恋 2020-12-09 10:34

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. Her

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-09 10:51

    In case someone is looking for a Swift version (based on @WarrenBurtons answer).

    AppDelegate

    @NSApplicationMain
    class AppDelegate: NSObject, NSApplicationDelegate {
        var window: NSWindow?
    
        func applicationDidFinishLaunching(_ aNotification: Notification) {
            // Insert code here to initialize your application
            window = NSWindow(contentViewController: RootViewController())
            window?.makeKeyAndOrderFront(self)
        }
    }
    
    class RootViewController: NSViewController {
        override func loadView() {
          self.view = NSView()
          self.view.frame = NSRect(x: 0, y: 0, width: 600, height: 400)
      }
    }
    

    NSApplication subclass

    import Cocoa
    
    class Application: NSApplication {
        let strongDelegate = AppDelegate()
    
        override init() {
            super.init()
            self.delegate = strongDelegate
        }
    
        required init?(coder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    }
    

    Info.plist entry

    
    
    
    
        ...
        NSPrincipalClass
        $(PRODUCT_MODULE_NAME).Application
        ...
    
    
    

    I've also created a gist for this, that I will keep up to date for new Xcode / Swift versions. https://gist.github.com/florieger/7ac5e7155f6faf18666f92f7d82f6cbc

    Edit: Make sure to delete the Main.storyboard / MainMenu.xib, otherwise you might end up with two Windows in the UI Debugger.

提交回复
热议问题