Mac O’Clock
Published in

Mac O’Clock

Auto Layout in Swift: Adding constraints easily

How to add constraints programmatically

Introduction

Auto layout allows us to create adaptive screens that are should be equally compatible with all screen sizes and orientations, The constraints make sure our views will adjust to any size changes without having to manually update frames or positions.

What is the problem with the Auto layout?

Writing constraints can be quite exhausting if you write the code programmatically using pure UIKit. Today, I’ll show you how to make extension methods which would make it easier.

I want to create four methods :

  1. anchor : to pin a view with four edge
  2. setSize: to set a fixed size for a view
  3. center: to center a view
  4. proportionalSize : to set a percentage size with a parent view

Now let’s start with the anchor method, which will take four nullable constraints with padding for each of them

Now I would assume I want to pin a label to the four edges with a padding 10 of the main UIView so I can write the sinppet2 instead of writing snippet1

A clean way to write constraints

The second method is setSize, will take two CGFLoat parameters and set them to width and height anchor respectively

The third one is the center method to center a view with another ann also you can add some padding.

The fourth method is proportionalSize, Will set the view's size relative to a passed view.

Further reading :

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store