13
votes

This is my first app from scratch under iOS 8 and XCode 6, so these spacing issues have been killing me. In the below you can see I have an UIImageView that I want to be a square, but I want it to stretch across the width of the screen as well.It has a width and height value so when the app runs the screen is wider so it ends up a tiny box in the top left corner. I've tried messing around with the constraints in every way I could think of, but when I constrain it the image blows up to full size and covers everything going off the screen. How do I get it to stretch and keep the 1 to 1 aspect ratio?

enter image description here

EDIT Ok, I was wrong. It's not the UIImageView that's not adjusting, it's the entire view. enter image description here

3

3 Answers

9
votes

Use the image view content mode:

[self.imageView setContentMode:UIViewContentModeScaleAspectFill];

It seems like you also want the width of the frame to fill the screen. Use these constraints:

  • Distance to top, left, and right to 0.
  • Height equals to width constraint.
  • Image ratio 1:1 constraint.

Then the image view should be resized appropriately.

3
votes

Constrain both sides and top to superview. You can also say that, for example, width/height can be >= 320, which sometimes helps. But remember, it will only work in portrait, when you turn the UI to landscape, the image can never stay square while filling the width and being fully onscreen at the same time.

EDIT: the image should not try to stretch beyond screen bounds (in portrait) as long as you do not tell it that it should be "this far from the bottom"

EDIT - 2: Set the background view constraints to superview. all 4.

1
votes

I would set the frame programmatically and not use constraints at all. To do that

  1. Link the ImageView to an outlet in its View Controller
  2. Set the frame so the two values are equal

    frame.size.width/frame.size.height