2

I have a yellow UIView and a blue UIView. The height of yellow one is dynamic and changes. The height of a blue one is always two times smaller than the yellow one. How to set constraints to achieve this? Is it possible at all?

Basically:

How to set aspect ratio between any of two UIViews?

Bartłomiej Semańczyk
  • 59,234
  • 49
  • 233
  • 358

3 Answers3

5

Of course it is! You should set the constraint to Equal Heights between these two views and then change it's multiplier to 1:2 or 2:1 depending on which of the views is "first". In order to add a constraint control-drag from one view to the other.

constraint

Bartłomiej Semańczyk
  • 59,234
  • 49
  • 233
  • 358
Losiowaty
  • 7,911
  • 2
  • 32
  • 47
  • Pretty awesome answer, thanks:) – Bartłomiej Semańczyk Mar 11 '16 at 12:38
  • No problem. In future, please search first - http://stackoverflow.com/questions/27742897/autolayout-aspect-ratio-for-uiimageview-uiview . I didn't check at first, as it was faster to write the answer than to check for duplicates, though I'm marking the question as one ;] – Losiowaty Mar 11 '16 at 12:41
1

Make reference of height constraints of both the view. When you change height of the yellow UIView to some dynamic value x , change the hight constraints of the blue UIView to x/2 .

imagngames
  • 350
  • 7
  • 19
1

enter image description here

  1. Set height constraint of AView and make outlet of the constraint.

  2. Set EqualHeight of BView To AView.

  3. Set EqualHeight constraints multiplier as 1:2.

  4. Update height constraint as you want.

    @IBAction func buttonToggleAViewHeightClicked(sender: UIButton) {
    
    if sender.selected {
        constraintHeightAView.constant = constraintHeightAView.constant - 200
        sender.selected = false
    } else {
        constraintHeightAView.constant = constraintHeightAView.constant + 200
        sender.selected = true
    }
    
        UIView.animateWithDuration(0.5) { () -> Void in
            self.view.layoutIfNeeded()
        }
    
    }
    
Bharat Modi
  • 4,158
  • 2
  • 16
  • 27