htzfun
htzfun

Reputation: 1448

How to create view programatically with .xib?

I got a simple idea - suppose we have singletone object that works similar to local notifications - when it's called it should show message view on the current window, wherever user is now. Message view is contained in .xib and got next code

@IBDesignable class MessageView : UIView {

var view: UIView!

var nibName: String = "MessageView"

@IBOutlet weak var messageLabel: UILabel?
@IBOutlet weak var closeButton: UIButton?

@IBInspectable var message : String? {
    get {
        return messageLabel?.text
    }
    set {
        messageLabel?.text = newValue
    }
}

@IBInspectable var type : MessageType = .Info

// init

override init(frame: CGRect) {
    super.init(frame: frame)

   setup()
}

required init(coder aDecoder: NSCoder) {
    // properties
    super.init(coder: aDecoder)
   setup()
}

@IBAction func closeButtonTouched(sender: UIButton) {
    self.view.hidden = true
}

func setup() {
    view = loadViewFromNib()

    view.frame = bounds
    view.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight

    addSubview(view)
}

func loadViewFromNib() -> UIView {
    let bundle = NSBundle(forClass: self.dynamicType)
    let view = bundle.loadNibNamed(nibName, owner: nil, options: nil)[0] as! MessageView

    return view
}
}  

The problem comes when I'm trying to instantiate it through init(frame:). It crashes at runtime with next text Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<NSObject 0x174014ce0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key closeButton.' in loadNibNamed method.

So should I use init(frame:) or not? I don't get why this problems appears. I did everything like in tutorial, but it works if you don't create view programatically.

Here is the link for additional info about tutorial - https://www.youtube.com/watch?v=r5SKUXSuDOw.

Upvotes: 0

Views: 138

Answers (3)

Darko
Darko

Reputation: 9845

I experienced a similiar problem and went crazy about it. Eventually, after trying and checking everything, the only thing which helped was renaming the .xib file.

Upvotes: 1

Vikas Dadheech
Vikas Dadheech

Reputation: 1720

The problem is with the closeButton in your case as of now. The closeButton's outlet is not properly connected with the XIB.

Right click on your closeButton in XIB and connect it with the outlet in your class. Remove the file owner and it's outlet's for the view.

This error will be resolved.

Upvotes: 1

Zell B.
Zell B.

Reputation: 10286

As error state you didn't create proper connection between .xib and closeButton so this has nothing to do with view initialization.To fix this open the .xib file, selected close button and check for missing connections in connection inspector

Upvotes: 1

Related Questions