Search code examples
objective-cuiviewuikitios6autolayout

Custom Aspect Ratio with AutoLayout


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


Solution

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