3.2. Defining Horizontal and Vertical Constraints with the Visual Format Language
Problem
You want to be able to define constraints that change the way a UI component is horizontally or vertically aligned on its superview.
Solution
Use the H: orientation
specifier in the formatting string for your constraint to dictate
horizontal alignment and the V:
orientation specifier to dictate vertical alignment.
Discussion
I won’t pretend the Visual Format Language is easy to understand. It is indeed very cryptic. For this reason, I will give you a few examples that hopefully will clear things up. All of these examples will change the horizontal alignment of a button on the screen:
- The button has to maintain 100 points on each side from its superview’s edges.
H:|-100-[_button]-100-|
- The button has to have a left distance of less than or equal to 100 points from the left edge of its superview. It also has to have a width that is greater than or equal to 50 points and has to stay 100 points or less away from the right edge of its superview.
H:|-(<=100)-[_button(>=50)]-(<=100)-|
- The button has to keep a standard left distance from the left edge of its superview (standard distances are defined by Apple) and has to have a width of at least 100 and at most 200 points.
H:|-[_button(>=100,<=200)]
As you can see, the formatting might take you some time to get used to. However, once you get the hang of the basics of it, it will slowly start to make sense. The same rules apply for vertical alignment, which uses ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access