A light weight, clutter-free, declarative syntax to Autolayout. (⚠️ Requires Swift 5.7)
Overview
We all use Autolayout to arrange and position UI components in UIKit. And doing in code is quite an exercise to brain to imagine how this piece of code will take reflect on screen.
We need to think about buttons, labels, various controls, child views. All UI componenets and their relation in between, parent, child, siblings, safe area, layout guides, size classes 🤯.
Let’s try to make this little simpler with some inspiration from SwiftUI and a lesser known friend Swift KeyPaths.
AutolayoutExtension
A light weight, clutter-free, declarative syntax to Autolayout. (⚠️ Requires Swift 5.7)
Overview
We all use Autolayout to arrange and position UI components in UIKit. And doing in code is quite an exercise to brain to imagine how this piece of code will take reflect on screen.
We need to think about buttons, labels, various controls, child views. All UI componenets and their relation in between, parent, child, siblings, safe area, layout guides, size classes 🤯.
Let’s try to make this little simpler with some inspiration from SwiftUI and a lesser known friend Swift
KeyPaths
.The Point
We all have written code like this.
In above code, just to add the
leadingAnchor
tootherView
with respect toview
the whole line is very lengthy and wordy.What if we just write the same line using.
Much more clear, concise and readable at a glance.
Map
.constraint(equalTo:)
EqualTo
NSLayoutAnchor<Axis>
.constraint(equalTo:constant)
EqualToConstant
NSLayoutDimension
.constraint(greaterThanOrEqualTo:)
GreaterThanOrEqualTo
NSLayoutAnchor<Axis>
.constraint(greaterThanOrEqualTo:constant)
GreaterThanOrEqualToConstant
NSLayoutDimension
.constraint(lessThanOrEqualTo:)
LessThanOrEqualTo
NSLayoutAnchor<Axis>
.constraint(lessThanOrEqualTo:Constant)
LessThanOrEqualToConstant
NSLayoutDimension
Modifiers
There 3 in-built constraint modifiers available.
.constant(_ constant: CGFloat)
.priority(_ priority : UILayoutPriority)
.id<ID: Hashable>(_ id: ID)
Example