Team6Labs
Team6Labs

Reputation: 175

How to instantiate NSViewController in Swift?

My current Swift code of

         var appBundle = NSBundle.mainBundle()
         let controller: ViewController = ViewController.init(nibName:        "ViewController", bundle: nil)
    self.window.contentView.addSubview(controller.view)
    controller.view.frame = self.window.contentView.bounds

is getting two errors. One is "Expected member name or constructor call after type name" and the other is "() is not convertible to 'ViewController'. For reference, ViewController is a class that inherits from NSViewController.

Both of the errors are occurring on the second line of code. Thanks in advance.

Upvotes: 6

Views: 7469

Answers (2)

Goodtime
Goodtime

Reputation: 111

I had to make the initialization of the view controller a global constant in order for it to work throughout my app. After racking my brain, I found that it was working locally, so making it global (putting it outside the AppDelegate class. works for me without the "nil" error)

//global constant
let viewController = ViewController(nibName: "ViewController", bundle: NSBundle.mainBundle())

class AppDelegate: NSObject, NSApplicationDelegate {
    @IBOutlet var window: NSWindow

func applicationDidFinishLaunching(aNotification: NSNotification?) {

    //links and loads the view to the main window
    self.window.contentView.addSubview(viewController.view)
    viewController.view.frame = self.window.contentView.bounds

    //works locally and elsewhere as long as viewController is global!
    viewController.statusField.stringValue = "TESTING"
    println(viewController.statusField)

    } 
}

Upvotes: 0

drewag
drewag

Reputation: 94773

In swift you don't call init on classes to instantiate them. You leave out the init and just put the arguments right after the type name:

let controller = ViewController(nibName: "ViewController", bundle: NSBundle.mainBundle())

or, you shouldn't need to provide the nibName if it matches the name of the class:

let controller = ViewController()

Upvotes: 8

Related Questions