0
votes

I have a UIView with 3 UIViews as its subviews. I have set layout constraints for these subview as fixed aspect ratio. i.e if the screen size changes their width will change but aspect ratio will always be the same.

Now i have also made width of the UIView (the red one as shown in screen shot) changing as the screen size changes. But i am struggling to make constraint for height of this view. what i want is its height should be set according to the total height of the subviews inside it.

since the height of the subviews will change if the width of the screen changes, because i have made their aspect ratios fixed.

As of right now i have made height of the Red superview fixed. but i want it to be variable according the total height of all the subviews inside it.

Here is the screen shot of my viewcontroller and its preview.

enter image description here

As you can see there is some space remaining because of the fixed height of red super view.

Details of the constraints i have added so far are as bellow.

Main Red SuperView

Main Red SuperView

**1st (Top), 2nd (Middle), 3rd (Bottom) Subviews respectively **

enter image description here

3
As @Bannings has said in his answer, remove the height constraint on the red view and simply add a bottom constraint to the red view for your 3rd view. You were so close with what you had 8^).Rory McKinnel

3 Answers

3
votes

You can add a bottom constraint from the 3rd view to its superview, then you have to remove the fixed height constraint of the superview.

1
votes
  1. Add an outlet for the height constraint of the red view if you haven't done it already.

  2. If you are doing this in viewDidLoad, call layouIfNeeded in controller's view.

  3. call for every subview, setNeedUpdateConstraints and layoutIfNeeded.

  4. Then calculate your desired red view's height (I would do 3*subview.frame.size.height + topPadding + bottomPadding) and set the red view's height xconstraint constant to this.

  5. call setNeedUpdateConstraints and layoutIfNeeded on red view.

0
votes

To support same behaviour in all resolution. you need to set layout as follow.

Red View enter image description here

UIView Top

enter image description here

UIView Middle

enter image description here

UIView Bottom

enter image description here

hope this help you.