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
leadingAnchortootherViewwith respect toviewthe 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:)EqualToNSLayoutAnchor<Axis>.constraint(equalTo:constant)EqualToConstantNSLayoutDimension.constraint(greaterThanOrEqualTo:)GreaterThanOrEqualToNSLayoutAnchor<Axis>.constraint(greaterThanOrEqualTo:constant)GreaterThanOrEqualToConstantNSLayoutDimension.constraint(lessThanOrEqualTo:)LessThanOrEqualToNSLayoutAnchor<Axis>.constraint(lessThanOrEqualTo:Constant)LessThanOrEqualToConstantNSLayoutDimensionModifiers
There 3 in-built constraint modifiers available.
.constant(_ constant: CGFloat).priority(_ priority : UILayoutPriority).id<ID: Hashable>(_ id: ID)Example