简体   繁体   中英

swift: Adjust UIView height based on constraints inside

I have a UIView container, that has left/top/right constraints against the super view. So the dimensions are dynamic, except for height. It does not have bottom constraint

This view has content inside (labels and so on). These elements also have constraints against each other and the super view ( to justify em )

Label1

-> Label2.top : Label1.bottom (+left and right of superview)

Label2

-> Label3.top : Label2.bottom (+left and right of superview)

Label3

and so on.

Labels have dynamic size, so, i can't get for sure what is the height of the label. It uses attributed strings. So calculating the subviews rects is not the solution

What i want to achieve is to set proper height of the main container considering constraints I am tired of googling, all i get is some frame rect manual calculations, which dont not work with constraints.

This are the constraints for elements inside:

    self.view.addConstraint(NSLayoutConstraint(
        item:self.view, attribute:.Trailing,
        relatedBy:.Equal, toItem:label,
        attribute:.Trailing, multiplier:1, constant:0))

    // left
    self.view.addConstraint(NSLayoutConstraint(
        item: label, attribute:.Leading,
        relatedBy:.Equal, toItem:self.view,
        attribute:.Leading, multiplier:1, constant:0))

    // Top
    self.view.addConstraint(NSLayoutConstraint(
        item:parentView, attribute: positionConstraint,
        relatedBy:.Equal, toItem:label,
        attribute:.Top, multiplier:1, constant:0))

Help me please!

I was just running into the same issue on an app I'm building. I'm using the Storyboard editor, so I'm not totally sure on the programmatic component, but if you add constraints for the vertical spacing in all the components within the view, then you just need to set a bottom space constraint on the bottom component inside the view.

http://cl.ly/image/2Y0y121s1e2V/download/Image%202014-11-19%20at%2013%3A59%3A15.png

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM