1
votes

I am having a weird auto layout with xib file/class issue. I have created a custom notification view (UIView subclass) in Swift that uses a xib file.

  • When the device is in portrait orientation on load, the notification is fine.
  • When I rotate to landscape, again the notification is fine (however, the button interactions somehow become disabled/non-respondent)
  • When I rotate back to portrait orientation, the xib view (i.e. "self") expands to a random height (notice the "yellow" background, that is set by: self.backgroundColor = UIColor.yellowColor()

Nothing in my code is setting the frame or constraints after the initial adding to the view controller. I have adjust every auto layout constraint in the xib file I could think of, and continue to have this problem.

Here are some screenshots: enter image description hereenter image description here

2

2 Answers

2
votes

Try to add a height constraint to the view. At the end of the list of constraints you have: - Vertical space (which i guess it's a vertical space to top - Horizontal space - Horizontal space - Add a height constraint for the view so that it never resizes its height

1
votes

Ok solved it. So the problem is, you can't have auto layout references setup in IB from a xib to an external UIViewController (since they don't know about each other until you programmatically add the xib as a subview). So you have to programmatically create the constraints.

Here is how I did it:

    // Manual constraints required since view is a xib file being added to an external view controller
    self.setTranslatesAutoresizingMaskIntoConstraints(false)
    var constraintHeight = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 0, constant: 44)
    self.addConstraint(constraintHeight)
    var constraintWidth = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: self.presentingViewController?.view, attribute: NSLayoutAttribute.Width, multiplier: 1, constant: 1)
    self.presentingViewController?.view.addConstraint(constraintWidth)
    var constraintTop = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: underView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0)
    self.presentingViewController?.view.addConstraint(constraintTop)