Cesare
Cesare

Reputation: 9419

Why is this object not positioned properly with Auto Layout?

I place an image view (content size: aspect fit) on my base layout. I create the trailing, leading and bottom constraints and set their constants to 0.

enter image description here

This doesn't happen when the image is smaller than the view:

enter image description here

Though, the image isn't positioned properly on the iPhone - it appears almost centered - while it is on the iPad. Perhaps its intrinsic content size is too big? Why is this happening?

Upvotes: 2

Views: 118

Answers (2)

jcaron
jcaron

Reputation: 17710

As you haven't set a top, aspect ratio, or height constraint on your image view, iOS falls back to the intrinsic content size (the actual size of the image) for the height only (the width is set by the leading/trailing constraints). If the image is wider than the screen, it will result in an image view that is as tall as the original image, but with the with set to the screen width.

Then, as you have the content mode set to Aspect Fit, iOS places your resized image inside the image view, and leaves lots of blank space around it.

One option to resolve this is to add an aspect ratio contraint on the image view, matching the aspect ratio of the image inside it. This will result in a correct height for the image view.

Upvotes: 1

Sandeep Bhandari
Sandeep Bhandari

Reputation: 20379

beyowulf was correct i believe. You should try changing the background color of imageview. If you change the imageview background color, you will realise that imageview always obeys your auto-layout constraint.

Now why not image?? Its because you asked it not to :) aspect fit will try to resize the image still maintaining the aspect ratio :) when the size of the image is too large i.e greater than the size of imageview frame, image covers the full frame of imageview and maintains the aspect ratio as well. Meaning if width is greater than screen width, image will cover the imageview frame width and takes a corresponding height for that width.

Thats why in first case your image covers full imageview frame where as in second where image size is small covers only space required :)

If on the other hand you want image to cover imageview frame always either fall back to scale to fill or aspect fill based on your requirement.

Happy coding :)

Upvotes: 0

Related Questions