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)
Author by
Admin
Updated on July 09, 2022Comments
-
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 over 9 yearsIs this doable from interface builder too?
-
fabb over 9 yearsYes it is since Xcode 6! In the Pin Tool there now is an option for Aspect.
-
Evgenii over 9 yearsI think it needs to swap NSLayoutAttributeHeight and NSLayoutAttributeWidth. Right now it says 3:4 and not 4:3.
-
D6mi over 8 yearsAlso, 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.