Auto layout Constraints in Swift

Updated 28 February 2021

Save

We will start with the small introduction with Auto layout Constraints in Swift.

AutoLayout is a system that makes it easy to support multiple screen sizes with just one interface by making the same interface react to changes. AutoLayout is a constraint-based layout system that gives developers the ability to create interfaces that respond to the changes in screen size and device orientation.
Without using auto layout, it would be very hard for you to create an app that supports all screen resolutions.

 

Auto layout Constraints in Swift using Interface Builder

Setting up the constraints through Interface Builder

Create a new Xcode project. Select Single view app.

Open Main.storyboard and add a few elements from the library. Drag the following onto the view controller:

Auto layout in storyboard
  1. Select Button (Tap) and open Align menu and check Horizontally in Container and Vertically in Container, then click  on Add 2 constraint.
  2. Now, Select Label(Hello world) and open Add new Constraint menu on the bottom-right and enter 20 to make a 20-point constraint to its nearest bottom neighbor and check Horizontally in Container
set button Auto layout constraints
set label Auto layout constraints

3. Now, select both buttons at the same time and, in the Align menu, check Leading Edges.

select both elements

Now check the app in different size screen.

Implementing Auto Layout Constraints in Swift programatically

There are different techniques you can use when implementing Auto Layout programmatically.

Writing constraints by using Layout Anchors

Let’s create a sign- in page.

First of all, we need to set the all fields to translatesAutoresizingMaskIntoConstraints equals to false. This is to prevent the view’s auto-resizing mask to be translated into Auto Layout constraints and affecting your constraints.

After that, you start by set constraints. we use NSLayoutConstraint to set the constraints.  The NSLayoutConstraint class defines a relationship between two objects.

 

LayoutAnchor

LayoutAnchor represents a single constraint, which can be either constant (e.g., fixed-width or height), or relative to another constraint (e.g., leading or trailing).

When activating or deactivating lots of constraints at once, it’s more efficient to pass them as an array to activate() and deactivate() respectively.

Now, run the app.

Autolayout contraints by code Iphone Xs
Autolayout contraints by code Ipad 3rd gen landscape
For other blogs Please click here

 

author
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Start a Project


    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home