0

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

iamhx
  • 472
  • 6
  • 24

2 Answers2

1

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.

Josh Homann
  • 15,933
  • 3
  • 30
  • 33
  • I've never added constraints programmatically, how do I achieve this? – iamhx Apr 25 '17 at 07:36
  • Use NSLayoutAnchor and set the constraints as outlined above. I have an example here: http://stackoverflow.com/questions/26180822/swift-adding-constraints-programmatically/40184218#40184218 – Josh Homann Apr 25 '17 at 17:11
0

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)
elk_cloner
  • 2,049
  • 1
  • 12
  • 13