OS X addsubview from xib in swift

眉间皱痕 提交于 2019-12-04 19:35:12

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)

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!