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
If you select Aspect Ratio for multiple items, Auto Layout chooses the width of one of the items for the numerator and the height of another item for the denominator. To change the initial aspect ratio, edit the Multiplier field of the Attributes inspector for the constraint.
In the “Aspect ratio” form field, type 16 and 9. Select the height as the property to change. Clicking "Apply" will resize the image's height to 90px.
A size that specifies the ratio of width to height to use for the resulting view.
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];
Here is the syntax for Swift 3:
NSLayoutConstraint(
item: item,
attribute: .width,
relatedBy: .equal,
toItem: item,
attribute: .height,
multiplier: width / height,
constant: 0)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With