Getting fancy with UIView anchors and state changes
Jul 6, 2017
2 minute read
If you prefer coded user-interfaces rather than designers (Xcode Interface Builder or Xamarin designers) you will surely like this API (available from iOS9+). It´s very readable, easy to maintain and feels more natural compared to the old one.
Every UIView has now a number of NSLayoutAnchor properties
that can be used to create constraints (NSLayoutCostraint):
Creating a constraint does not mean it will be active by default and you´ve got do it explicitly:
It´s really easy to create UIView method extensions. For instance, to center a view in its parent (following the above sample):
Now let´s adjust a view to its parent bounds:
And now let´s make a shortcut to set the width and height:
Consider playing around with all anchors and Constraint...To() methods. You can make literally anything.
Those method extensions above return an array of constraints so we can deactivate/activate them later. Consider a set of constraints like a visual state we can store in a variable:
States can get even more complex by chaining the constraints from multiple objects:
Simply deactivate the old constraints and activate the new ones:
With the basic blocks in place, let´s create a new extension to get fancy with state changes: