Auto Layout in Swift: Adding constraints easily
How to add constraints programmatically
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 :
- anchor : to pin a view with four edge
- setSize: to set a fixed size for a view
- center: to center a view
- 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
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 :