Custom Aspect Ratio with AutoLayout

JaviAlgaba picture JaviAlgaba · Sep 20, 2012 · Viewed 20.3k times · Source

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

Answer

JaviAlgaba picture JaviAlgaba · Sep 21, 2012

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];