Xcode - Weird issue with xib and auto layout (xib expands to random height)

戏子无情 提交于 2019-12-11 09:13:46

问题


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:


回答1:


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




回答2:


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)


来源:https://stackoverflow.com/questions/26794718/xcode-weird-issue-with-xib-and-auto-layout-xib-expands-to-random-height

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!