12

I have been playing around with iPhone interface building using only code and not using IB.

Now I'm facing the following problem:

How can I set an image to have a width based on the main view it is located on and to let it have a margin of for example 50 pixels on both sides. ( it should also work with rotation so the width should be flexible ).

I have tried setting the size with frame.size.width - 50 for example but this doesn't work when the screen rotates. Another thing I tried is using the autoresizing masks but I'm not completely understanding how this works.

Does one still need to set a frame for an image or is this completely overruled by the autoresizing masks? And if it's overruled how can I give the image a fixed height and a flexible width?

The book I'm using ( advanced iOS4 programming ) is not very clear in this matter and most examples I find on the net are for interface builder.

Thanks for your time.

Kind regards, Jasper

Jasper
  • 175
  • 1
  • 1
  • 7

2 Answers2

50

Horizontally:

  • Resize keeping fixed left/right margins: UIViewAutoresizingFlexibleWidth
  • Keep size and same distance from the left: UIViewAutoresizingFlexibleRightMargin
  • Keep size, stay centered: UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin
  • Keep size and same distance from the right: UIViewAutoresizingFlexibleLeftMargin

Vertically:

  • Resize keeping fixed top/bottom margins: UIViewAutoresizingFlexibleHeight
  • Keep size and same distance from the top: UIViewAutoresizingFlexibleBottomMargin
  • Keep size, stay centered: UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin
  • Keep size and same distance from the bottom: UIViewAutoresizingFlexibleTopMargin

Combine one from the first section with one from the second with a |. For example, to have it resize horizontally and keep the same size and distance from the top vertically, you'd use UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin.

You can use other combinations to do some more tricky things, but those are the basics.

Anomie
  • 92,546
  • 13
  • 126
  • 145
  • So basically how I now see it.. you set the frame for a certain object. and then you specify these values in case the screen rotates so it knows how to respond ? – Jasper Mar 02 '11 at 16:15
  • Yes, or in case the superview changes size for any other reason. For example, the "in-call status bar" could appear causing the top-level UINavigationController to resize its content area, or you could just change the `frame` of the superview for reasons of your own. – Anomie Mar 02 '11 at 16:41
0

You probably want this:

[myImageView setAutoresizingMask:UIViewAutoresizingFlexibleWidth];

That will keep the margins static and resize the width.

Jeff Kelley
  • 19,021
  • 6
  • 70
  • 80