0

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

Stephen Fox
  • 12,750
  • 19
  • 46
  • 51

1 Answers1

0

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.

Ivo Leko
  • 662
  • 1
  • 10
  • 19
  • I now get the following error `fatal error: init(coder:) has not been implemented` although I have implemented the `required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") }` – Stephen Fox Mar 15 '15 at 16:32
  • @StephenFox check this: http://stackoverflow.com/questions/24036393/fatal-error-use-of-unimplemented-initializer-initcoder-for-class – Ivo Leko Mar 15 '15 at 18:44