Search code examples
iosswiftuitextfieldaddsubviewcustom-view

Show UIView with xib on textFieldDidBeginEditing


I made a custom uiview class with a xib and I want to be able to show it on the screen with textFieldDidBeginEditing but I can't seem to figure it out.

In myCustomView:

required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)

    //Load the interface

    NSBundle.mainBundle().loadNibNamed("customNib", owner: self, options: nil)
    self.addSubview(self.view)
}


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

What I did and works is in IB I put a view in my interface and linked it to my customView class.

Now, I want to show this view with custom class programmatically.

If I do this in my textFieldDidBeginEditing (I have a textfield in my main view):

var myView: myCustomView = myCustomView(frame:CGRectMake(100, 100, 100, 100))
    myView.backgroundColor = UIColor.redColor()

self.view.addSubview(myView)

I get a red square on the screen but it does not "load" the xib.

Am I not asking the good question or am I doing something wrong? Could you guys poit me in the right direction?

I went through all the similar questions here and could't find the solution.


Solution

  • Just the stupidest of the things, i initialised myView with init(frame) and hadn't put my xib on the screen. This works:

    override init(frame: CGRect) {
        super.init(frame: frame)
    
        NSBundle.mainBundle().loadNibNamed("customNib", owner: self, options: nil)
        self.addSubview(self.view)
    }