Sunday, February 14, 2016

iOS Auto Layout Notes - 1

This post has written about 
  • Adding auto layout constraints to UI object by using interface builder
  • Changing auto layout constraints by using swift language
Auto layout constraints can be defined to work with different Size classes. Size classes that is applied to different devices and orientations can be change with the below Pop over in the interface builder.

Since UI components of this application is needed to be fit to all the UIs height and width size class of Any is selected here.

There is a UIImageView object on the UIViewController of this class. To center it horizontally on the screen select the UIImageView click on the align button to display Add New Alignment Constraints pop up.

On the pop up menu Select Horizontally in Container and then click on the button Add 1 Constraint.

UIImageView needs to be 10 point below from the top layout guide. And it need to have width and height of 200 points. To do that click on the pin button to show pop up that can be used to add constraints for above requirements.

Once the constraints were set by using pin pop up like above click on Add 3 Constraints to add them to UIImageView.

To see changes on the storyboard. Click on the Resolve Auto Layout Issues button that shows a   menu like below .Then click on Update Frames.

That will remove orange color lines if there are them and adjust UI dimensions to reflect constraints.

Change Auto layout Constraints with Swift Code

Create IBOutlet to UIImageView width and height constraints.

@IBOutlet weak var imageHeight: NSLayoutConstraint!
@IBOutlet weak var imageWidth: NSLayoutConstraint!


Write a method like below to change Auto layout constraints which is referred through outlets by using swift code.

func resizeImage(size: Int){
    imageHeight.constant = CGFloat(size)
    imageWidth.constant = CGFloat(size)
}


Value of instance of  NSLayoutConstraint can be changed by assigning new CGFloat value to that instance's constant property.

No comments:

Post a Comment