Auto Layout Tip #1: Multiplier
An Auto Layout constraint can be described in the form of a linear equation. For example, for an equality constraint:
FirstItem.Attribute1 = (SecondItem.Attribute2 * Multiplier) + Constant
Apple's Auto Layout documentation explains this concept in more detail. In this post we're going to focus on what is perhaps the most commonly misunderstood part of this equation, the multiplier.
Equal Widths constraint
I came across an interesting Auto Layout problem recently where I wanted to resize a button relative to the size of an image view above it.
My requirements were:
- The button should fit its content without compression.
- There should always be at least 20 points between the button and the left and right edges of screen.
- The button should size itself to be slightly wider than the width of the image view above it (10% wider to be exact) if it has more horizontal space than it needs.
So, on wide screens the button will be 1.1 times the width of the image view. On narrow screens the width of the button will increase to fit its content, but only until it reaches 20 points from the edge of the screen (shown by the red guides in the below screenshot). At this point the button will be forced to start compressing its content.
The solution
- Give the button a high horizontal content compression resistance priority (e.g. 900) and low content hugging priority (e.g. 100).
- Add >= 20 constraints to the left and right edges of the button (priority 1000).
- Add an Equal Widths constraint between the button and the image view with a multiplier of 1.1 (priority 950, constant 0). Edit the constraint and change the relation to Greater Than or Equal.
Remembering our equation from earlier, the last constraint can be expressed as follows:
button.width >= (imageview.width * 1.1) + 0
A common mistake
Often when you have a constraint with a multiplier, the constant is 0 (as it is here), but it doesn't have to be. If you're using a constant together with a multiplier, just remember the multiplier is applied to the attribute first and then the constant is added to the result. A mistake I sometimes come across is a constraint that is unintentionally offset with a constant of 1. For multipliers the default is 1, but for constants the default value is 0 (which makes sense when you think of a constraint in terms of a linear equation).
Aspect Ratio constraint
Multipliers can be decimals like 1.1 in the previous example, but they can also be ratios. The image view in that example has an Aspect Ratio constraint with a multiplier of 240:221. Regardless of what size the image is displayed on screen, this constraint makes sure the aspect ratio stays the same.
Further reading
If you'd like to learn more about multipliers and test your Auto Layout skills, have a go at my recent Auto Layout Workshop.