Swiftly85 Swiftly85 - 5 months ago 196
Swift Question

OS X addsubview from xib in swift

I'm trying to add a new sub view form a nib using swift for OS X.

So far i've:


  • created a new "Cocoa Application"

  • added a new "Cocoa Class" called "TestSubView" as a subclass of NSViewController with a XIB file



I want to add this subview to my main view when the application loads.

in my ViewController ( the ViewController for the main window ) i have.

import Cocoa

class ViewController: NSViewController {

override func viewDidLoad() {
super.viewDidLoad()

let newSubView = TestSubView();
self.view.addSubview(newSubView.view);

}

override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}


}


But i'm getting the following error

Failed to set (contentViewController) user defined inspected property on (NSWindow):
-[NSNib initWithNibNamed:bundle:] could not load the nibName: temp.TestSubView in bundle (null).


I realise i will need to size and position this subview but I can't seem to get to that point.

I've spent the better part of a day trying to figure this one out so any help would be greatly appreciated.

Answer

I finally got this thing to work. My new code looks like

import Cocoa

class ViewController: NSViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let subview = TestSubView(nibName: "TestSubView", bundle: nil)!
        self.view.addSubview(subview.view)
    }

    override var representedObject: AnyObject? {
        didSet {
        // Update the view, if already loaded.
        }
    }

}

Found with the help of the docs & this answer

It was suggested that if the nib name and the class name are the same you shouldn't need to declare nibname: (as i'd tried to do originally) but the docs didn't mention this - explains why it didn't work!

For prosperity, this worked for me with Xcode 6.1.1 on OS X Yosemite (10.10.1)