Thursday, 28 April 2016

How to use Autolayout in UIView design in IOS tutorial - Beginner


Auto Layout Tutorial
This tutorial is for beginner in Autolayout in IOS app development. We will learn basics of auto layout in this post. Autolayout in IOS is an excellent tool to make your user interface workable on all devices. Now with the size classes introduction it is much easier to to create a single screen and make it adaptable to all iPhone models. In this tutorial we will learn about auto layout, that is how to use auto-layout while creating user interface in iOS app development.

Step 1: Create a new project and name it AutoLayout-Part1
Create new project
Create new project
Step 2: Open Main.storyboard and you will see an empty View Controller.

Step3: Drag an UIImageView to your viewController, now our requirement is to make this a background image but with 10 pixel gap from all sides i.e from top, bottom, left, right side.

Drag UIImageView to your ViewController
Drag UIImageView to your ViewController
Step 4: Adjust your UIImageView as 10 pixel gap from all four sides of View Controller. Give a background colour to your UIImageView.
Giving background Colour to UIImageView
Giving background Colour to UIImageView

At this moment, we place our UIImageView with gap of 10px. If you run this in all devices then you will see something like as shown below

iPhone 6 simulatoriPhone 4 simulator

Step 5: As we did not get the desired result by simply placing UIImageView on View Controller. We have to use Auto-Layout. Select your UIImageView and hold control key, move your cursor to UIView object of View-controller.

Adding constraints to UIImageView


Step 6: A black window will appear, click on Leading, Trailing, Vertical spacing as shown in the picture below, then click add constraints. This will add four constraint to our UIImageView.

Adding leading, trailing, top, bottom constraints


Leading space to container margin: This will tell compiler that we want 10 px of space from leading side of the screen i.e. from our x axis from left side.

Trailing space to container margin: This will tell compiler that we want 10 px of space from trailing side of the screen i.e. from our x axis from right side.

Vertical spacing to Top Layout Guide: This will tell compiler that we want 10 px of space from top side of the screen i.e. from our y axis from top side.

Vertical spacing to Bottom Layout Guide: This will tell compiler that we want 10 px of space from bottom side of the screen i.e. from our y axis from bottom side.

Step 7: Finally run your code and your will get the desired result.

Running app in iPhone 6 Simulator
Source Code: Click here to download the source code

No comments:
Write comments