In this episode, I'd like to take a moment to discuss the anatomy of a constraint, the fundamental building block of a user interface driven by Auto Layout. Remember that user interfaces created with Auto Layout define constraints. The constraints describe the relationships between the views in the user interface. The Auto Layout engine then inspects these constraints and calculates the frame of every view in the view hierarchy.
What Is a Constraint
What is a constraint? A constraint is nothing more than a linear equation, describing the relationship between two items in the view hierarchy. The Auto Layout engine inspects the constraints of the user interface and evaluates the equations defined by the constraints. That evaluation should always result in one possible layout. The resulting layout should be unambiguous and satisfiable. We revisit these terms later in this series.
This is what the blueprint of a constraint looks like. It's nothing more than an equation that describes the relationship between two items, item A and item B. Let's look at some examples.
Some Examples
In the previous episode, we created a user interface with a label and a button. This is what the constraint looks like for the top constraint of the label. It defines that the label's top edge must be 30 points below the top of the safe area layout guide. We discuss layout guides later in this series. Don't worry about it for now.
This is another example from the previous episode. The constraint defines that the top edge of the button should be 8 points below the bottom edge of the label.
Items and Attributes
The items in an equation of a constraint can be views or layout guides, and they should be part of the view hierarchy. The attributes in the equation are the attributes of the items that are constrained. You have size attributes, width and height, and location attributes, such as top, leading, trailing, and bottom.
Relationship
The relationship defines how the two sides of the equation relate to one another. You have an equal to relationship, a greater than or equal to relationship, and a less than or equal to relationship. It defines the relationship between the left and right side of the equation.
Multiplier
The multiplier is the value the right attribute is multiplied by. For example, to define the aspect ratio of a view, you could set the multiplier to a specific value. In this example, the aspect ratio of the view is set to 3/2 by defining that the width of the view should be equal to 1.5 times the height of the view.
Constant
The constant of the equation is the value added to the right attribute. In this example, the constant is 8.0, offsetting the top of the button 8 points below the bottom of the label.
In the next episode, we take a closer look at constraint priorities.