iOS - Auto Layouts - IOS

What is iOS layputs?

Auto-layouts are introduced in iOS 6.0. When we are about to use auto-layouts, our deployment target must be 6.0 and higher. Auto-layouts assists us in creating interfaces that can be employed for multiple orientations and for multiple devices.

What is the Goal of Our Example?

We will add two buttons that will be placed in a certain distance from the middle of the screen. We will also try to add a resizable text field that will be placed from a given distance from above the buttons.

What is Our Approach?

We will add a text field and two buttons in the code also with their constraints. The constraints of every UI Elements will be created and added to the super view. We will have to disable auto-resizing for every of the UI elements we add in order to get the desired output.

What are the Steps Involved?

  • Step 1. Create a simple view-based application.
  • Step 2. We will edit only ViewController.m and it is as follows −

Points to Note

In steps marked 1, 5, and 8, we just programmatically added two buttons and a text field respectively.

In the remaining steps, we created constraints and added them to the respective super views, which are actually self-views. The constraints of one of the left buttons is as shown below −

We have constraintWithItem and toItem which will decide between which UI elements we are creating the constraint. The attribute will decide on what basis the two elements are joined together. "relatedBy" will decide how much effect the attributes will have between the elements. Multiplier is the multiplication factor and constant will be added to the multipler.

In the above example, the X of leftButton is always greater than or equal to -60 pixels with respect to the center of the super view. In the same way, other constraints are also defined.

Output

After running the application, we'll get the below output on the iPhone simulator −

iOS - Auto Layouts

When we alter the orientation of the simulator to landscape, we will get the below output −

iOS - Auto Layouts

After running the same application on iPhone 5 simulator, we will get the below output −

iOS - Auto Layouts

When we alter the orientation of the simulator to landscape, we will get the below output −

iOS - Auto Layouts

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

IOS Topics