Start a Project

Auto layout Constraints in Swift

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:

  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

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

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.

For other blogs Please click here

 

Exit mobile version