Marco
Marco

Reputation: 81

XCode doesn't load a custom view

I have created a custom view for an error message.

I created an ErrorView.swift sub classing UIView and I created also an ErrorView.xib to use in Interface Builder.

In the identity inspector I set the custom class of the xib as ErrorView.swift but when I try to load this specific view it doesn't work.

Why? Can you help me?

This is the code:

My personalized class named ErrorView

Class ErrorView: UIView {
  class func errorInView(view:UIView, animted:Bool) -> ErrorView {
    println("ERROR VIEW LOADED")
    let errorView = ErrorView(frame: view.bounds)
    errorView.opaque = false
    view.addSubview(errorView)
    return errorView
  }
}

my xib:

http://i59.tinypic.com/23tnlev.png

This is the code I use in my ViewController to call the view.

let errorView = ErrorView.errorInView(self.view, animted: true)

Upvotes: 0

Views: 153

Answers (1)

JMFR
JMFR

Reputation: 809

The problem here is that you are not loading your xib, instead you are creating a new Error View in code.

If you add errorView.backgroundColor = UIColor.greenColor() after errorView is created, but before you add it as a subview you will see the screen turn green. I have posted this example as a gist.

If you want to create your view from the xib you will have to load the xib using the normal NSBundle.mainBundle() call.

let errorView = NSBundle.mainBundle().loadNibNamed("ErrorView", owner: self, options: nil)[0] as ErrorView

instead of creating the view with the ErrorView(frame:)

This example is also a gist.

Upvotes: 1

Related Questions