Cesare Cesare - 6 months ago 26
Swift Question

AutoLayout not working with embedded Xib file

I have a nib with a label in it, which is centered vertically and horizontally using Auto Layout. I declared a subclass of

UIView
and loaded the nib file in it.

I then added an
UIView
to my main view controller and assigned the new subclass to it. The problem is that the label of the nib file is not centered to the view, it doesn't follow the AutoLayout constraints.

enter image description here

Download test project. Why is this happening?

Answer

In your case you have to do it like:

import UIKit

class CustomView: UIView {

    @IBOutlet var testView: UIView!

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!
        NSBundle.mainBundle().loadNibNamed("CustomView", owner: self, options: nil)
        self.addSubview(self.testView)
        self.testView.frame=CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)
        //or
        self.testView.frame=self.bounds
    }
}
Comments