Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 388
JaviAlgaba Avatar asked Sep 20 '12 10:09

JaviAlgaba


People also ask

What is Autolayout aspect ratio?

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.

How do you make a figma 16 9?

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.

What does aspect ratio do in Xcode?

A size that specifies the ratio of width to height to use for the resulting view.


2 Answers

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];
like image 121
JaviAlgaba Avatar answered Oct 11 '22 22:10

JaviAlgaba


Here is the syntax for Swift 3:

NSLayoutConstraint(
  item: item,
  attribute: .width,
  relatedBy: .equal,
  toItem: item,
  attribute: .height,
  multiplier: width / height,
  constant: 0)
like image 20
user1615898 Avatar answered Oct 11 '22 21:10

user1615898