Saturday, January 11, 2014

Autolayout and Orientation

This is a sample project which demonstrates following:
  • Use of Autolayout to setup proportional views
  • Use of Autolayout programmatically to move subviews to support different orientation
Consider following contrieved example where we have different layout for landscape and portrait for set of controls. 

Landscape




Steps and Explanation
Divide sections of the screen into subview
Group the controls into some sort of organization based on relationship among them. Use subviews to arrange them as in sample above. The subviews does not need to have visual characteristics as background color or borders. The colors used above is just for easier visualization.

Define the horizontal and vertical constraints using visual programming language To make the task of defining constraints easier inspect the expected result for both orientation. Come up constraints for the leftView and rightView in relation with containerView.

For Landscape,
  • Horizontal Constraints: [superView]-[leftView]-[rightView]-[superView] ==> H:|-[leftView]-[rightView]-|
  • Vertical Constraints: [superView]-[leftView]-[superView]  ==> V:|-[leftView]-| and [superView]-[rightView]-[superView]V:|-[rightView]-|
  • leftView.width = factor x rightView.width (Factor for same width = 1.0)
  • leftView.height = rightView.height (Factor for same height = 1.0)
For Portrait,
  • Horizontal constraint: [superView]-[leftView]-[superView] ==> H:|-[LeftView]-| and [superView]-[rightView]-[superView] ==> H:|-[rightView]-|
  • Vertical constraint: [superView]-[leftView]-[rightView]-[superView] ==> V:|-[leftView]-[rightView]-|
  • leftView.height = factor x rightView.height (Factor for same height = 1.0)
  • leftView.width = rightView.width (Factor for same width = 1.0)

Code updateViewConstraints method
For Landscape:
For Portrait:
Complete source code at: https://github.com/kartikshah/AutoLayoutTemplate

No comments: