Constraint is a simple wrapper for iOS Auto Layout that has a very natural syntax
Usually you will use the Constraint library on an instance of the (descendant class of) UIView you want to constrain. Every call returns the UIView again so it's very easy to chain all of your layouts like this:
icon
.attach(top: 20,
leading: 10,
bottom: 0,
trailing: 10)
.size(width: 24, height: 24)Also there's the possibility to add various modifiers to offset constraints:
image.attach(top: 0.orMore, bottom: 12.defaultLowPrioritized)
// These are also chainable
label.attach(bottom: 0.orMore.prioritized(to: UILayoutPriority(800))If you want to save a certain Offset for reuse you can do that like this:
let offset = 0.orMore.defaultLowPrioritized.respectingLayoutGuidesIt's possible to respect any layout guide (like iPhone X's Safe Area) by using respectingLayoutGuide / layoutGuideRespecting
It's also possible to work with arrays of views. For example it's now possible to space an array in a certain direction or to attach them all to their parentviews. The most used function is simply to add them as subviews:
[view1, view2, view3].addedAsSubviews(to: superView).attach()
As you see this method is also fluent.
Sometimes you need to store the constraints that are generated. In this case you need to call the static methods on the Constraint class directly as follows:
private var messageHeight: NSLayoutContraint?
// ...
messageHeight = Constraint.height(50, for: message).activatedIn this case you will have to add the constraint manually to the view. It's the maximum amount of flexibility but a bit more work.
These are all the publicly exposed extensions to UIView. They are based upon the options you see in Interface Builder. Here's a short overview to see how they are related:
- The
align()functions map to the first 7 options that are relations between two equal views - The
center()functions are used for the last two options of the Align screen, where asubviewis centered in it'ssuperview
Spacing to nearest neighboris covered by all of theattach()functionsWidth,Height,Equal WidthsandEqual Heightsare covered bywidth(),height()andsize()Aspect Ratiois handled by theratio()functionAlignis an alias for the Edges in the Align screen and therefore is covered byalign
This method is used to space the view related to is superview. You can define all sides at once, every side separately and leave some sides out. It takes Offsetable as it's parameter which means you can either use a primitive like Int or CGFloat or you can send an Offset directly.
This is the most basic way to use attach. You can define an offset or accept the default of 0:
view.attach()
view.attach(offset: 12)This version lets you specify which sides are going to be attached. You can define an offset or accept the default of 0:
view.attach(sides: [.top, .leading, .trailing], 12)This is the most flexible way to use this API. Every side can have it's own separate definition which is Offsetable so can be mutated further when needed.
view.attach(top: 0, trailing: 12) // Does not apply the bottom and leading constraints
view.attach(top: 0.orMore) // It's possible to use it with primitives and still modify the priority or relation type
view.attach(leading: 12.orLess.defaultLowPriority) // These can also be chained
view.attach(bottom: Offset(0, .orMore, respectingLayoutGuide: true, priority: .defaultLow)) // Means the same as view.attach(bottom: 0.orMore.layoutGuideRespecting.defaultLowPriority)respectingLayoutGuide / layoutGuideRespecting means it respects the layout guides, like in the root view of a ViewController where you expect it to respect the Safe Area sometimes.
The default is to not respect the layout guides.
Center lets you center the view inside another view, where it defaults to the superview. It's also possible to specify another view that needs to be part of the same view tree
view.center(axis: .both) // Centers the view on both the X and Y axis of it's superview
view.center(axis: .x, adjusted: 10, priority: .defaultLow) // Wants to center it's X to it's superview, then adjusts it +10 pixels and applies a low priority to itAlign is used where you want to align two views that are not in a parent / child relationship.
Centers can be aligned much like the center() API does for parent / child views:
view.align(axis: .x, to: anotherView, adjustment: 10) // Wants to center it's X to anotherView, then adjusts it +10 pixelsIt also allows you to align a side instead of the middle:
view.align(.leading, 12, otherView) // Aligns it's leading side to the leading side of otherView + 12 pixelsIf you want to align multiple sides (much like attach does) you can do this too:
view.align([.top, .leading, .bottom], 0, to: otherView)Space the view to another view in any direction.
registerButton
.space(20, .above, reconfirmButton)
.space(8, .below, usernameLabel, .orMore, priority: .defaultLow)These functions are used to set the size of a UIView. You can set the width and height also related to the width or height of another view.
otherView
.size(width: 100, .orMore, height: 50)
view
.width(200)
.height(100)size() also accepts a CGRect as a parameter which can be handy if you for example want to copy frame.size
view.size(superview.frame.size)You can also make it relative to another view:
view.height(relatedTo: superview, adjusted: 10)Ratio sets the ratio between the width and the height of view.
view.ratio(of: 2) // Makes the width twice as much as the height
view.ratio(of: 3, to: 2) // Makes the width height have a ratio of 3:2Alternatively, you can also call it with a CGRect. This is very handy if you want your UIImageView always have the same ratio as your UIImage:
view.ratio(avatarImage.size)With vanilla UIKit nesting ViewControllers requires an even bigger amount of effort, taking at least three lines of code before even getting to the point where you can start to set up your constraints:
addChild(viewController)
parentView.addSubview(viewController.view)
viewController.didMove(toParent: self)Without Constraint you would add at least another five lines of NSLayoutConstraint code to just align the edges to the parent view:
viewController.view.translatesAutoresizingMaskIntoConstraints = false
viewController.view.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
viewController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
viewController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
viewController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = trueWhen decomposing your Views into smaller Subviews is so hard, it's not very unexpected that many UIKit developers tend to put so much stuff into one ViewController. It's very disencouraging to do the right thing.
The embed function takes away a lot of the boiler plate code. Embedding ViewControllers now looks like this:
embed(viewController: childViewController) // Was: 3 lines of code to add the child
.attach() // Was: 5 lines of code to align the child
When it gets that easy to add child ViewControllers, you will use it way more often.
This is the 0.9 release of this library but it already has been used in a few projects internally and all of the major kinks have been worked out. The last major hurdle for full functionality is being able to capture all created constraints, so they can be turned on and off programmatically.
To run the example project, clone the repo, and run pod install from the Example directory first.
- Swift 4 or higher
- iOS (or related platforms)
Constraint is available through Swift Package. CocoaPods support still exists, but will be less frequently updated.
- Open the project you want to add the dependency to
- Go to
File>Swift Packages>Add Package Dependency - Enter
https://github.com/LucasVanDongen/Constraintin theEnter package repository URLtextfield - Click
Next - Change the version you want or leave it as is
- Click
Next - Once it's done installing tap
Finish
To install it, simply add the following line to your Podfile:
pod 'Constraint'Built for Blue Rhizome by Lucas van Dongen, [email protected] @ lucasvandongen.dev
Constraint is available under the MIT license. See the LICENSE file for more info.

