Scale a UIView automatically on orientation change to scale proportionaltely to fit in parent view

Mr Wolf picture Mr Wolf · Jan 1, 2013 · Viewed 10.5k times · Source

A UIImage view set to "Aspect Fit" will automatically dynamically scale it's image to fit within the current bounds of the UIUmageView, while maintaining the image's proportions. A UIView set to "Aspect Fit" does not seem to have this same effect on it's sub-views.

I have tried to set the parent view via code, with the code below, and tried several variations on the auto-resizing mask ( I am not using auto layout). Am I missing something obvious, or do I need to write a little code to compute the right scale for my sub-view based on the current size of the parent view?

[self.view setContentMode:UIViewContentModeScaleAspectFit];

Answer

jrturton picture jrturton · Jan 1, 2013

From the documentation:

The content mode specifies how the cached bitmap of the view’s layer is adjusted when the view’s bounds change.

For an image view, this is talking about the image. For a view that draws its content, this is talking about the drawn content. It does not affect the layout of subviews.

You need to look at the autoresizing masks in place on the subviews. Content mode is a red herring here. If you can't achieve the layout you need using autoresizing masks, then you need to implement layoutSubviews and calculate the subview positions and frames manually.