Cesare Cesare - 8 months ago 45
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

and loaded the nib file in it.

I then added an
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?


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.testView.frame=CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)