How to adjust super view 's height base on subview's size in XIB?

和自甴很熟 提交于 2020-01-02 03:48:21

问题


In xcode 6 ,i create a xib for a custom view (named: ViewA,got a RED background color) ,and ViewA's xib got a file size 600*600, in ViewA ,I put a subview labelB (got a GREEN background color )in it ,and labelB's numberOfLines = 0 ,so labelB'height is variable , I want the ViewA 's height changed based on labelB's height (e.g ViewA.bottom = labelB.bottom + 10), and I have already pin the labelB's top,bottom,trailing,leading to ViewA, but it still doesn't !work ,the ViewA's height is always 600 ,no matter what label's height is . How can i achieve this goal in auto layout? thanks


回答1:


Using Auto Layout, here's what you need to do:

  1. Make sure you aren't adding fixed width and/or height constraints to any of your subviews (depending on which dimension(s) you want to dynamically size). The idea is to let the intrinsic content size of each subview determine the subview's height. UILabels come with 4 automatic implicit constraints which will (with less than Required priority) attempt to keep the label's frame at the exact size required to fit all the text inside.

  2. Make sure that the edges of each label are connected rigidly (with Required priority constraints) to the edges of each other and their superview. You want to make sure that if you imagine one of the labels growing in size, this would force the other labels to make room for it and most importantly force the superview to expand as well.

  3. Only add constraints to the superview to set its position, not size (at least, not for the dimension(s) you want it to size dynamically). Remember that if you set the internal constraints up correctly, its size will be determined by the sizes of all the subviews, since its edges are connected to theirs in some fashion.

  4. Make sure you change to view's translatesAutoresizingMaskIntoConstraints property value to NO before applying any constraints.

That's it. You don't need to call sizeToFit or systemLayoutSizeFittingSize: to get this to work, just load your views and set the text and that should be it. The system layout engine will do the calculations for you to solve your constraints. (If anything, you might need to call setNeedsLayout on the superview...but this shouldn't be required.)

You can check the original answer here



来源:https://stackoverflow.com/questions/27014273/how-to-adjust-super-view-s-height-base-on-subviews-size-in-xib

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