How to create a piano using iOS 9 Auto Layout
Issue #22
In the beginning, people use frame and Autoresizing Mask, then they use Auto Layout, then iOS 9 encourages them to use NSLayoutAnchor
, UILayoutGuide
and UIStackView
For more convenient Auto Layout, check How to make Auto Layout more convenient in iOS and Anchors
NSLayoutAnchor
The NSLayoutAnchor class is a factory class for creating NSLayoutConstraint objects using a fluent API. Use these constraints to programmatically define your layout using Auto Layout.
It has 3 subclasses
NSLayoutDimension
- func constraintEqualToConstant(_ c: CGFloat) -> NSLayoutConstraint!
NSLayoutXAxisAnchor
- Allows working with horizontal constraints
- Prevent these
1 | // This constraint generates an incompatible pointer type warning |
NSLayoutYAxisAnchor
- Allows working with vertical constraints
- Prevent these
1 | // This constraint generates an incompatible pointer type warning |
UILayoutGuide
Previously, we used dummy views to aid constraints. Now we use UILayoutGuide
Define an equal spacing between a series of views
See full gist
1 | let space1 = UILayoutGuide() |
Layout guides can also act as a black box, containing a number of other views and controls
See the full gist
1 | let container = UILayoutGuide() |
layoutMarginsGuide
Margins are now represented as layoutMarginsGuide
, a subclass of UILayoutGuide
topLayoutGuide and bottomLayoutGuide
In the container example, we saw how we must use NSLayoutConstraint
with the topLayoutGuide
. topLayoutGuide
and bottomLayoutGuide
are object conforming to UILayoutSupport
protocol
layoutFrame
The layout guide defines a rectangular space in its owning view’s coordinate system. This property contains a valid CGRect value by the time its owning view’s layoutSubviews method is called.
In the above container example, the container layout guide frame is
1 | (16.0, 40.0, 343.0, 21.0) |
Piano
See Piano on Github on how to create a Piano using UILayoutGuide
, NSLayoutAnchor
and UIStackView