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
Mark Cranston
1,817 PointsAdding 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
Stepan Ulyanin
11,318 PointsYou 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
Mark Cranston
1,817 PointsMark Cranston
1,817 PointsWhere do I specify the ratio?
Stepan Ulyanin
11,318 PointsStepan Ulyanin
11,318 PointsIt 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
heightandwidthto be 2/3 and then use Aspect Ratio, it should keep the aspect the same through the life cycle of the objectMark Cranston
1,817 PointsMark Cranston
1,817 PointsWhere do I type in the actual ratio?
Stepan Ulyanin
11,318 PointsStepan Ulyanin
11,318 PointsYou should do something like:
height: 90 width: 60
which means that width is 2/3 of height and then do the Aspect Ratio
Stepan Ulyanin
11,318 PointsStepan Ulyanin
11,318 PointsThen in your
size inspectoryou can see all the constraints and there will be theMultiplierthat will look like 2:3Mark Cranston
1,817 PointsMark Cranston
1,817 PointsSorry, 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?
Stepan Ulyanin
11,318 PointsStepan Ulyanin
11,318 Pointshttps://www.dropbox.com/s/7z4sdxw9fh2ut3y/Screen%20Shot%202015-09-25%20at%2010.04.36%20PM.png?dl=0
Once you added the
aspect ratioyou can change the constraint in yoursize 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 exceptionMark Cranston
1,817 PointsMark Cranston
1,817 PointsThank you SO much! It is working great now!
Stepan Ulyanin
11,318 PointsStepan Ulyanin
11,318 PointsI'm glad it helped!