Joseph Lin
Joseph Lin

Reputation: 3334

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

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!

Upvotes: 31

Views: 25899

Answers (3)

Dave Cole
Dave Cole

Reputation: 2765

This guide from Apple really helped me - it outlines two approaches, one where you turn off AutoLayout for certain subviews and set frames directly, and another where you use pure AutoLayout via code.

https://developer.apple.com/library/ios/technotes/tn2154/_index.html

Upvotes: 0

rdelmar
rdelmar

Reputation: 104082

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.

Upvotes: 34

rudi
rudi

Reputation: 376

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

Upvotes: 36

Related Questions