简体   繁体   中英

How to load xib to UIView subclass, Swift, iOS

I have a .xib file called ContentView that I want to use as the view for a class called ContentView , however I cannot seem to load it.

class ContentView: UIView {
    override init() {
        super.init(frame: CGRect(x: 0, y: 0, width: 500, height: 500))
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        fatalError("init(coder:) has not been implemented")
    }
}

I'm aware that you can load a xib using the following method but this gives a error when I do so:

var contentViewXib: NSArray = NSBundle.mainBundle().loadNibNamed("ContentView", owner: nil, options: nil)

I have also set the xibs files owner to ContentView and set its Custom Class in interface builder to the class I want to use it with.

Any help is appreciated. Thanks

If you set File's owner to ContentView, then view in your XIB is not ContentView, it is normal UIView that ContentView can retrieve.

In the init method of ContentView, call NSBundle.mainBundle().loadNibNamed() just like you wrote in your question and then type:

self.addSubview(contentViewXib[0])

You will also need to set constraints or autoresizing mask for this new view.

EDIT: Another solution is to select view directly (not File's Owner) and change its class to ContentView.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM