Custom Aspect Ratio with AutoLayout

20,489

Solution 1

I figured out.

//Given a childView... 
NSLayoutConstraint *constraint =[NSLayoutConstraint
                           constraintWithItem:childView
                           attribute:NSLayoutAttributeWidth
                           relatedBy:NSLayoutRelationEqual
                           toItem:childView
                           attribute:NSLayoutAttributeHeight
                           multiplier:4.0/3.0 //Aspect ratio: 4*height = 3*width
                           constant:0.0f];
            [childView addConstraint:constraint];

Solution 2

Here is the syntax for Swift 3:

NSLayoutConstraint(
  item: item,
  attribute: .width,
  relatedBy: .equal,
  toItem: item,
  attribute: .height,
  multiplier: width / height,
  constant: 0)
Share:
20,489
Admin
Author by

Admin

Updated on July 09, 2022

Comments

  • Admin
    Admin almost 2 years

    Let's say I have a UIView that contains a child UIView which has to be 4:3. I want to solve this problem using AutoLayout in code.

    I've been struggling with AutoLayout but I haven't figured out yet how to do this.

    Do you know how to solve this problem?

    Thank you very much.

    I attach an image to explain better what I mean. http://d.pr/i/d0Oc

  • fabb
    fabb over 9 years
    Is this doable from interface builder too?
  • fabb
    fabb over 9 years
    Yes it is since Xcode 6! In the Pin Tool there now is an option for Aspect.
  • Evgenii
    Evgenii over 9 years
    I think it needs to swap NSLayoutAttributeHeight and NSLayoutAttributeWidth. Right now it says 3:4 and not 4:3.
  • D6mi
    D6mi over 8 years
    Also, a good thing to add here, is that you cannot change the multiplier of constraints once they're created - the multiplier property's read-only. One's not able to change the multiplier even by using key paths. The way to proceed is to remove the constraint at hand and recreate it with the new multiplier.