Press "Enter" to skip to content

Applying Constraints on Buttons in Xcode

Hello everyone!
Today I’m going to talk about Constraints.
Constraints has always been an issue and pain in the neck to everyone, because they can be confusing sometimes. I cannot make your pain go away completely but I can try to help you lessen it.
Let’s consider an example:
I have taken a total of 5 buttons. Placed two on the two top corners, the other two on the bottom two corners and one in the center as you guys can see in the picture below:
(The View Controller size is of an iphone 5s)

Screen Shot 2015-06-05 at 4.04.25 am

When built and run on an iPhone 6 simulator, these were the results.

iOS Simulator Screen Shot 05-Jun-2015 4.05.57 am

So, we are gonna start by First button. Press the Document Outline button, Press the First button and press control and drag it to the view as shown in the picture.

Screen Shot 2015-06-05 at 4.01.48 am

Since you want that button to stay in the top left corner, select the Top Space to Top Layout Guide.

Screen Shot 2015-06-05 at 4.07.06 am

Repeat the above process again but this time select Leading Space to Container Margin.

Screen Shot 2015-06-05 at 4.09.14 am

Select Second and do the same as did for First and Select Top Space to Top Layout Guide for it as well.

Screen Shot 2015-06-05 at 4.09.49 am

Now control drag Second again and this time select Trailing Space to Container Margin, as we want it on the right most top.

Screen Shot 2015-06-05 at 4.10.03 am

Select the Third button and since we want the third button to appear in the center irrespective of the screen size, Select Center Horizontally in Container.

Screen Shot 2015-06-05 at 4.36.43 am

and then next. Select Center Vertically in Container.

Screen Shot 2015-06-05 at 4.36.55 am

Now Turn to Fourth button, Select Bottom Space to Bottom Layout Guide since it is required at the bottom.

Screen Shot 2015-06-05 at 4.13.54 am

After that, Select Leading Space to Container Margin.

Screen Shot 2015-06-05 at 4.14.08 am

At last, the Fifth button Select Bottom Space to Bottom Layout Guide

Screen Shot 2015-06-05 at 4.14.45 am

and Trailing Space to Container Margin.

Screen Shot 2015-06-05 at 4.14.57 am

After following all the above steps you’re going to achieve this when run on iPhone 6 simulator.

iOS Simulator Screen Shot 05-Jun-2015 4.16.15 am

I have uploaded this project on my Github so that you guys can download and test it.
If you guys have a question, please leave a comment.

Good day!

Author: kodesnippets

Be First to Comment

Leave a Reply

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