Erik
Erik

Reputation: 2530

Using UIImageView together with constraints

I've a UIImageView that holds a profile image in my app. The aspect is "Aspect Fit". But I have some problems.

I've pinned a contraint from the UIImageView to the larger UImageView above and with the leading space to superView.

enter image description here

but it looks like this on runtime:

enter image description here

Way too big and placed wrongly.

It also looks like this in IB:

enter image description here

What should I be doing to achieve the right behaviour here?

Thanks! Erik

Upvotes: 0

Views: 3767

Answers (2)

iamyogish
iamyogish

Reputation: 2432

Its all due to the Intrinsic Content Size. Just like UILabel and UIButton resizes itself based on its content, the UIImageView also resizes itself based on the size of image its going to hold.

The intrinsic content size is really good for labels and buttons but not so good when it comes to UIImageView. Because the image you're going to set to the UIImageView can actually be bigger than the screen size and we don't want our image view to be as big as the image itself.

So one simple solution for this is to set the Width and Height Constraints or aspect ratio constrainton the image view so that the size of the image view will be constant.

HTH :)

Upvotes: 5

Rog
Rog

Reputation: 17170

You image view is resizing itself based on the image you set it to display.

This behaviour very useful in (e.g.) text views where you want a view to grow to display all the text. It's sometimes less useful in image views which are part of a static UI.

One solution it to add constraints to the view to keep the size you set: right drag from the view to itself and then add a width constraint just as you would any other contstraint then either add a vertical height constraint or an aspect ratio constraint.

Another solution is to provide correctly sized assets so the view autosizes to the correct dimensions.

Upvotes: 1

Related Questions