iamhx
iamhx

Reputation: 472

Autolayout not working for my nib when added subview

I've created an xib and loaded the nib in my viewDidLayOutSubviews:

I then added the subview:

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    if (myCustomView == nil) {

        myCustomView = Bundle.main.loadNibNamed("Help", owner: self, options: nil)?.first as? HelpView
        self.view.addSubview(myCustomView!)
    }
}

My constraints are all set up correctly in my xib (toggling between devices look okay), however when I launch the app on a different device the autolayout is not updated. How do I fix this? Thank you!

Edit:

Toggled for iPhone 7, but launching for iPhone 7 Plus enter image description here

Toggled for iPhone 7 Plus, launching for iPhone 7 Plus enter image description here

Upvotes: 0

Views: 792

Answers (2)

elk_cloner
elk_cloner

Reputation: 2149

just add this line below

self.view.addSubview(myCustomView!)

myCustomView.translatesAutoresizingMaskIntoConstraints = false;
//Views to add constraints to
let views = Dictionary(dictionaryLiteral: ("myCustomView",myCustomView))

//Horizontal constraints
let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|[myCustomView]|", options: nil, metrics: nil, views: views)
self.view.addConstraints(horizontalConstraints)

//Vertical constraints
let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[myCustomView(SpecifyFixedHeight)]|", options: nil, metrics: nil, views: views)
self.view.addConstraints(verticalConstraints)

Upvotes: 0

Josh Homann
Josh Homann

Reputation: 16327

Your constraints may be setup correctly in your nib, but you don't have any constraints when you call self.view.addSubview(myCustomView!), so the frame is just going to be whatever it is in the nib file. You need to constraint myCustomView to self.view. Give it equal width, center X, equal top and a fixed height (or use the intrinsic height) and it should be fine. Make sure you turn off translatesAutoresizingMaskIntoConstraints.

Upvotes: 1

Related Questions