Sunday, February 12, 2012

Why UIView's autoresizingMask does not work

I was trying to use to autoresizingMask in a UILabel to resize the width when the device is rotated. Following my first instinct, I wrote label.autoresizingMask = UIViewAutoresizingFlexibleWidth. However, the label didn't resize. Why?

There are a few values for the mask such as UIViewAutoresizingNone, UIViewAutoresizingFlexibleRightMargin, UIViewAutoresizingFlexibleLeftMargin, and UIViewAutoresizingFlexibleHeight. I tried to use UIViewAutoresizingFlexibleRightMargin or UIViewAutoresizingFlexibleLeftMargin but there was no difference.

Wait a minute. If we need to set those values to enable flexible margins, width, and height, what does it mean if we leave them unset? If I only set the autoresizingMask property to UIViewAutoresizingFlexibleWidth, it actually means Flexible Width AND Fixed Left Margin AND Fixed Right Margin. Even though the width is flexible, the fixed left and right margins do not allow the flexible width to expand or shrink.

Now, it is clear that when we need to set flexible width or height, we must also set  at least a corresponding margin to be flexible at the same time. For example, if we want the label to expand the end of the text (assuming that the text goes from left to right) when the width changes, we should set autoresizingMask to UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleRightMargin so that the label can expand it's width at the right margin.