OS X addsubview from xib in swift

11.9k views Asked by At

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.

2

There are 2 answers

0
Swiftly85 On BEST 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)

6
Mundi On

A nib is really nothing but an XML file with view information in it. You have to get it from the application bundle and get one of the views contained in it explicitly. You are perhaps confounding views and view controllers (your attempt to extract view from newSubView suggests that).

Try this:

let subview = NSBundle.mainBundle().loadNibNamed("TestSubView", 
   owner:self, options:nil)![0]! // maybe no final unwrapping "!" in Swift 3
self.view.addSubview(subview)

Make sure the xib is really called the name you are using and contains at a least one view (otherwise the two unwrapping ! above will crash your app).