Auto-Layout Constraint: How to make a view maintains its width/height ratio when resized?

25,789

Solution 1

You can add an aspect ratio constraint in IB by control dragging from the view to itself and choosing aspect ratio.

Solution 2

I don't think you can do that in IB, but in code, it can be done like this (iv is my outlet to the image view):

    [self.iv removeConstraints:self.iv.constraints];
    NSLayoutConstraint *con1 = [NSLayoutConstraint constraintWithItem:self.iv attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1  constant:100];
    NSLayoutConstraint *con2 = [NSLayoutConstraint constraintWithItem:self.iv attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self.iv attribute:NSLayoutAttributeWidth multiplier:.66 constant:0];
    [self.iv addConstraints:@[con1,con2]];

This explicitly sets the height to 100, and the width to height ratio to 3:2.

Share:
25,789
Joseph Lin
Author by

Joseph Lin

iOS developer

Updated on May 02, 2020

Comments

  • Joseph Lin
    Joseph Lin about 4 years

    In the interface builder we can pin height, pin width, make two views width equally, but how do I set the constraints so that when a view is being resized, it maintains its width/height ratio?

    In my particular case, I have an UIImageView in my view controller. When the view resizes, I'd like my image view to resize, but maintain a 3:2 width:height ratio. Is it possible to do it in IB? Is it possible to do it with code?

    Thanks!

  • Joseph Lin
    Joseph Lin over 11 years
    Thanks! con2 is exactly what I need.
  • Rob
    Rob over 11 years
    +1 I haven't found an IB way to do this either. I do it via code, too.
  • Joseph Lin
    Joseph Lin about 10 years
    Update: Xcode 5.1 supports doing that in the IB (finally).
  • hqt
    hqt over 9 years
    i think @rudi post now should be marked as accepted answer, because new version of xcode can support this behavior. And almost all developers now use xcode version 5 or above. :)
  • valvoline
    valvoline over 9 years
    definitely this is the right answer. however, if you don't like the control-dragging way, click the second icon on the bottom right of your interface builder (the one with the square at the center) and be sure to check the "Aspect ratio" flag.