Initialize subclass of NSViewController without xib file

I am currently writing an OS X application using Swift 2. I want to create an interface without XIB or storyboard. The problem I am facing is initializing a custom ViewController in which I can put my views.

Here is my AppDelegate:

@NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { @IBOutlet weak var window: NSWindow! var viewController: MyViewController? func applicationDidFinishLaunching(aNotification: NSNotification) { viewController = MyViewController() self.window.contentView!.addSubview(viewController!.view) } func applicationWillTerminate(aNotification: NSNotification) { // Insert code here to tear down your application } } 

And MyViewController:

 class MyViewController: NSViewController { var textField: NSTextField? override func viewDidLoad() { super.viewDidLoad() textField = NSTextField(frame: NSRect(x: 10, y: 10, width: 100, height: 100)) textField!.bezeled = false textField!.drawsBackground = false textField!.editable = false textField!.selectable = false textField!.stringValue = "TEST" self.view.addSubview(textField!) } } 

The problem is that when I add the viewController as a contentView , I get the following error and the view does not load.

 2015-12-06 17:34:18.204 Test[9682:1871784] -[NSNib _initWithNibNamed:bundle:options:] could not load the nibName: Test.MyViewController in bundle (null). 

I'm not sure what I'm doing wrong - any help would be appreciated.

+7
cocoa swift macos
source share
1 answer

From the NSViewController documentation :

If you pass nil to nibNameOrNil, then nibName will return nil and loadView will throw an exception; in this case you must call setView: before the call, loadView is opened or overrides.

The initializer for MyViewController() uses nil for the name nibName.

Two possible fixes:

1. Set the view to AppDelegate

 func applicationDidFinishLaunching(aNotification: NSNotification) { viewController = MyViewController() viewController!.view = NSView() // added this line; edit to set any view of your choice self.window.contentView!.addSubview(viewController!.view) } 

On the other hand,

2. Override loadView in your subclass of ViewController

 import Cocoa class MyViewController: NSViewController { var textField: NSTextField? override func loadView() { self.view = NSView() // any view of your choice } override func viewDidLoad() { super.viewDidLoad() textField = NSTextField(frame: NSRect(x: 10, y: 10, width: 100, height: 100)) textField!.bezeled = false textField!.drawsBackground = false textField!.editable = false textField!.selectable = false textField!.stringValue = "TEST" self.view.addSubview(textField!) } } 
+19
source share

All Articles