Step 1: Create a new project and name it AutoLayout-Part1
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 |
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 |
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
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.
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.
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.
Source Code: Click here to download the source code