How to implement AutoLayout in code and why do it? Explained in SnapKit.

Abdurrahman Sanli
Appcent
Published in
11 min readFeb 25, 2021

This article will cover your entire journey on creating user interfaces for your app “programmatically” without touching any visual elements or storyboards.

If you are looking for a TL;DR and would like to experiment SnapKit concepts by yourself; you could scroll down to the SnapKit examples section at the bottom; otherwise you can continue reading on for a deeper understanding.

I. What is real?

How do we define existence of a solid matter in real world standards? We sure identify a piece of matter according to their positioning and depth in 3 dimensional axis.

In mobile application world however; objects appearing are 2 dimensional only, meaning they don’t have an inner depth which leaves us with 2 other dimensions to work with. In each of those dimensions; we are going to need a position, and a depth within the dimension.

In order for something to exist in a 2 dimensional space, it should have:

  • A point it starts from in vertical space.
  • A point it starts from in horizontal space.
  • A depth in the vertical axis a.k.a. ‘Height’
  • A depth in the horizontal axis a.k.a. ‘Width’

II. Different approaches on Auto-Layout

In order to explain a computer about positioning, width, height etc. of a UI element using auto-layout; you have several options where every option have their own pros and cons. We’ll try to go through them quickly.

1) Using a storyboard

Storyboards lets you to see scheme of the app all in one glance. This is their only advantage tho. While you can see your actual UI elements in ease; you still need to reference each of them in code in order to work with them. Plus you would have to define each constraint in the code in order to change them. Another downside is; they get bulky so quick. Delayed load times and being prone to conflicts (each storyboard with many controllers is a single file) makes them impossible to work with in real world projects.

2) Using XiBs

Just like storyboards you would see the UI elements; unlike storyboards however you see one XiB for each screen of your app which gets rid of the bulkiness of storyboards. Downsides are still you are being have to define the UI elements in code in order to work with them. Another downside is just like the storyboards; you would have to swap between code and UI every time.

3) Using SwiftUI

The first advantage is; its brand new, Apple’s own UI system. I’d go for this if it wasn’t too early for this at this time. If you are reading this in 2023; go for SwiftUI if you like. If you are reading this earlier however; consider that SwiftUI supports iOS 13 only; which means a significant part of your potential users won’t be able to use your app. Therefore this option is not much likely yet to be considered as an option by app companies.

4) Using native coding

There’s an old style of defining auto layout rules in Swift. This style however takes considerably long time to execute. While you get the benefits of coding UI without visual elements; syntax is bad for no good reason.

5) Using third party libraries (This is what we are going to do here)

This is the best option you could go according to my experiences in the industry. Using these libraries you get a nice looking syntax; you don’t have to redefine every element or constraint (UI rule) in code again and again, you can work without having to swap between code and UI screens; you will almost never get any conflicts compared to XiB’s or Storyboards. Listing of pros goes on and on. Cons is this being slightly advanced for someone who just started iOS Development, HOWEVER you can easily adapt yourself to it if you spend some time. Best known libraries for this are: 1)Snapkit 2)Purelayout. I used to work with Pure before; now I’m using Snapkit since I find it’s syntax nicer. In this tutorial we are going to continue explaining AutoLayout and we are going to implement it using Snapkit framework.

III. Where am I?

Hello

I’d like to introduce you with Sindy. She’s been so kind to help us today.

A. Positioning in vertical & horizontal axis

This is one of the two dimensions we need to define in order to create something in the UI. Within this dimension; we are going to define both a position (where the object stands); and a depth (how long space this object occupies in the dimension).

As we see here; Sindy stands in slightly lower left part of the screen. In order to define her position; we are going to work with both vertical and horizontal axises. For now we are talking about the vertical axis.

Vertical axis of Sindy is once again in slightly bottom part of the screen. We could define this in two ways: 1) Sindy is far away from top. 2) Sindy is closer to the bottom. Coding Sindy’s position is just as easy. We could tell the compiler either she is far from the top or closer to the bottom and in both ways she would appear the same.

Here for example we decided to define a top spacing in order to let the computer to understand Sindy’s vertical position and this is what the auto layout is about.

We could define this spacing in variety of different ways as mentioned in section II. In this tutorial however we are going to discuss the SnapKit way.

Don’t get your hands dirty with the code yet! Just hold your breath until you understand the concepts fully and get to the examples section.

Above is the sample code snippet to define a constraint for viewSindy. The constraint consists of the following basic rules:

  • “maker.top.equalToSuperview()” top of viewSindy equals to it’s superview meaning head of sindy would touch top of the screen.
  • “offset(277)” meaning head of sindy is off the point 277 points.

Please pay attention that this example was made to explain the vertical dimension using a top constraint. We could however define it with a bottom constraint as follows:

This would give us the same result in an average sized iPhone. These different approaches would result following outputs in huge screens such as iPads:

Code snippets shared above however are not enough to let the computer know where Sindy should stand in the manner of positioning since we only talked about vertical axis.

In order for a computer to understand how to lay down a view; it should know about 4 things: it’s vertical position, it’s horizontal position; it’s height & it’s width.

Now that we have implemented the vertical position constraint, we can add the horizontal one as follows:

These two constraints gives us the following set of rules:

This seems to be perfect.

Now Sindy not only knows where on a vertical axis she stands on; but she also knows about her horizontal axis as well.

These rules however are not enough alone by themselves in order to see her pretty face.

As Sindy doesn’t have a designated height or width; these rules we defined can still be met without Sindy appearing since she has no volume.

This will be explained in the next part.

B. Volume up — heights & widths

Please check for Sindy in the following picture:

You see; in computer programming; everything’s about rules. Outputs which seems to be wrong are mostly seems wrong because they are way too correct!

In this case for example; Sindy meets the top spacing requirements as well as leading spacing for horizontal positioning levels even tho -with no offenses to her- she’s just a 0 by 0 pixels of nothing.

In order to fix this; we should tell the compiler about Sindy’s height and width.

Let’s add a few lines to get the following code:

Well well; there goes our perfect Sindy!

These 4 lines of codes above will layout Sindy as seen on the left. You could do this to a UIView with a background color and get the same area painted. You can set these constraints to any kind of view including UIImageView, UITableView, UILabel, UIButton vice versa…

Even tho constraints we’ve given are a 140x140 box; Sindy still looks normal around the edges. Reason for this is; her UIImageBox includes white spaces around the Sindy. You can think it as she’s swimming in the middle of a 140x140 pool.

Now let’s head to the examples section!

IV. Examples

In order to begin with the following examples of this section; first thing to do is to start up your Xcode project and install the following pod:

pod 'SnapKit'

After the installation, go to your ViewController and add the following base code where we are going to fill with examples given here later on.

I’m not sharing any code directly so you could write them by yourself instead of copy pasting. Please always try to spare some time to type tutorial codes by yourself as a good practice. This way you will understand the concepts better.

What we are doing here is initializing 3 views with different colors.

Initializing those views won’t add them to our view but will get them ready to be added.

In the following examples; we are going to add views we are going to need just before we set constraints using SnapKit maker.

.

.

.

.

.

1) Single view centered

As seen in the both iPad Pro 12.9 and iPhone 12 Pro results; we end up with a 100x100 blue box centered in the superview. Just as we wrote and expected in the code above.

Also please notice that we have added view1 alone inside our container view (view of the view controller).

If we did add the other two views but we haven’t given them any constraints, they simply wouldn’t have appeared.

2) Big brother

Please take your time understanding this one.

First of all; in view1; we used centerX and centerY instead of directly setting to parents center. This way we can play with those two individually. We used it to give some offset to centerX and got the blue box lean to the left.

While adding the second view (view2-purple) we used side of the view1(blue) as a snapping point. We attached left of view2(purple) to the right side of view1(blue); we also set top of the view2(purple) to be equal with top of view1(blue). This is a pretty neat example about having relative relations about where your views stand.

3) Holy Cross

In this example I wanted view1(blue) to fill the entire screen with edges equal to superview.

I made two individual lines with other two views.

Have you noticed that horizontal purple view of our cross is a little bit off? Can you fix it by setting an offset so the purple part is closer to the top? (there are more than one solutions)

4) The Responsive Stack

This what we see here folks; is one of the most advanced cases of auto layout. If you understand this example well; you could simply do anything.

Have you noticed that in all of our previous examples we’ve simply set a static height and width to our views? But not with this one. What is happening here is; views calculate their width sizes according to sides of the screen. We also set height of each view to be equal with it’s own width so we keep the square aspect ratio. This way; when your screen gets larger; so does the views.

Please do notice that you wouldn’t want to do this with your content in most of the cases. Reason to that is: with larger screen devices; you simply want more of the content to be observed — not that you want your content to get bigger and you see same amount of content in screens no matter how large the screen is. Think it like you are browsing through news; you’d want to see as many articles as possible. This is however needed to be done in some cases depending about how you’d like your app to look.

Verdict

Using all these simple aspects of auto-layout; you can control your UI however the way you want.

There is no case of any UI complexity in which you wouldn’t be able to build. In iOS Development; anything is possible as long as you know how to do it.

I’d want to have more time writing about why it is the best to code your UI and how to make the most out of it by updating your constraints on the go and implementing sweet animations using these constraint values; these topics however couldn’t fit in this article and are yet to be discovered by your own research.

If you’d like me to cover more topics in this manner or if you got any ideas or questions about the article; please let me know in the comments. I’d like to share more advanced information about these topics depending on demand of iOS Developer community.

Fear no more and have fun playing with your constraints; iOS Developer!

Now you are ready.

--

--