AutoLayoutBuilder — my Swift package to reduce boilerplate code. by Chris Nevin | October, 2022

Take advantage of @resultBuilder to build DSLs for UIView constraints

We’re going to address some issues with this DSL:

  1. Establishment translatesAutoresizingMaskToConstrants To false
  2. repeat the same anchor twice
  3. repeat the same constant many times
  4. Code Structure: Layout code can be everywhere, this DSL aims to solve this through the use of nesting

Usually, when using auto-layout we have multiple blocks of code like:

It’s already starting to get hard to read and we’ve only added one scene, what happens when we have 10 scenes?

No wonder developers hate it when they need to hunt down auto-layout bugs, there’s a lot of reading involved!

Most developers are lazy. With that in mind, let’s remove all the cruft and make it more concise:

Let’s see how we can achieve this…

First, we need a way to reference singularities and arrays NSLayoutConstraints In the same block, we call it a . can do with protocol,

another, addSubview a. is using @resultBuilder which allows us to gather all NSLayoutConstraints We would like to apply.

At this point we really have everything we need to do something like this:

Already a huge improvement over what we had in the beginning, but let’s continue…

To make our constraints more readable we will need to store some information about them, for this example I am only going to refer to the four edge constraints we are going to use.

It provides some anchors that we can now reference/combine in our ConstraintBuilderapply it ConstraintBuilding First protocol…

There you can see that our anchors are being used in those 4 functions, by putting this in a protocol we can extend other types build This allows us to chain the constraints (ie .leading().trailing(),

Now let’s implement this protocol in our ConstraintBuilder Structure For this article, I’m going to make it simple and just make equalToSuperview() Celebration.

In the above example you can see that we can do combine with another obstacle inside of us build function, this is what allows us to chain our constraints. Now we can do our layout redView hence:

Since these are all values 20 We can combine this into a function:

Now we can do what we set out to do:

We can actually nest these calls as well:

Thanks for reading!

If you’re interested in incorporating it into your own project, below is information about the Swift package, it allows you to write even more concise code with relative constraints:

Leave a Comment