Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Adding Constraints to UIView

I have a UIView that is centered both vertically and horizontally, it also has a variable width constraints. I would like to add a height constraint that is proportional to the width. Basically I want to set a constraint to my view that is something like: height = width/2. How would I do this?

1 Answer

You can use "Aspect Ratio" that will preserve the ratio you are going to specify, just in the interface builder under "pin" in the bottom where you specify the constraints select Aspect Ratio

Where do I specify the ratio?

It is in the bottom of the interface builder: https://www.dropbox.com/s/i1m6qm0ef9ntcp0/Screen%20Shot%202015-09-25%20at%209.50.13%20PM.png?dl=0

So specify your height and width to be 2/3 and then use Aspect Ratio, it should keep the aspect the same through the life cycle of the object

Where do I type in the actual ratio?

You should do something like:

height: 90 width: 60

which means that width is 2/3 of height and then do the Aspect Ratio

Then in your size inspector you can see all the constraints and there will be the Multiplier that will look like 2:3

Sorry, I feel like I am being really dense, but just to clarify I type a value for the height in and it will keep that proportion when the width changes?

https://www.dropbox.com/s/7z4sdxw9fh2ut3y/Screen%20Shot%202015-09-25%20at%2010.04.36%20PM.png?dl=0

Once you added the aspect ratio you can change the constraint in your size inspector, just keep ratio and height, you can also add width but if it won't be in ratio with the height the app will throw an exception

Thank you SO much! It is working great now!

I'm glad it helped!