Understanding UIView autoresizing

Autoresizing is one of the most useful property for layouting the views in their hierarchies.

This property is often neglected by beginner iOS programmers and it is one of the most useful for laying out your user interfaces.

 Consider the situation where you want your view to resize when the device is rotated between portrait and landscape orientations. The learning(beginner or inexperienced) programmer will detect the screen rotation and then he will  explicitly set the “frame” property of all their views to fit the new screen size.

This approach is tedious and impractical way of manage your user interface.
Instead you can use the “autoresizingMask” property to describe how you want your view to adapt to orientation changes.

 Your options are:

 UIViewAutoresizingNone
 UIViewAutoresizingFlexibleLeftMargin
 UIViewAutoresizingFlexibleWidth 
 UIViewAutoresizingFlexibleRightMargin
 UIViewAutoresizingFlexibleTopMargin
 UIViewAutoresizingFlexibleHeight 
 UIViewAutoresizingFlexibleBottomMargin

Consider the example of a toolbar at the Top of your screen. If you want to have the toolbar stretch to fill the available width, but still remain at top of the window, you can say:


newView.autoresizingMask = (UIViewAutoresizingFlexibleWidth |
               UIViewAutoresizingFlexibleBottomMargin);

If you want do this in xib file the spring must look similar to below image



Using a bitwise “OR” (the “|” pipe character) you combine multiple options together into a single value that tells UIKit how you want your view to adapt to changes to the screen, and even to changes in your view’s superview.


Another example is an interface that has the standard round  button in the bottom-left corner of the screen.


newView.autoresizingMask = (UIViewAutoresizingFlexibleRightMargin |
               UIViewAutoresizingFlexibleTopMargin);


If you want do this in xib file the spring must look similar to below image



If you play with those values you can get around to resize your views  in almost all cases.

4 comments:

  1. Your picture for the "UIViewAutoresizingFlexibleWidth |
    UIViewAutoresizingFlexibleBottomMargin" is wrong. It should have the contraints on the top, left and right. The only flexible margin in the pic should be the bottom.

    ReplyDelete
  2. @ Anonymous the picture is correct
    setting in xib and setting in code is both are opposite try it in code you came to know.

    ReplyDelete
  3. Hi,

    Thank you for this simple tutorial. Beginners will easily understand about Auto-resizing.

    ReplyDelete
  4. Doesn't work, my damn map still stays narrow after a rotate.

    ReplyDelete