OS X addsubview from xib in swift

旧城冷巷雨未停 提交于 2019-12-09 23:18:02

问题


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.


回答1:


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)




回答2:


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



来源:https://stackoverflow.com/questions/27228362/os-x-addsubview-from-xib-in-swift

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