Using UIImageView together with constraints

独自空忆成欢 提交于 2019-12-11 20:42:19

问题


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.

but it looks like this on runtime:

Way too big and placed wrongly.

It also looks like this in IB:

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

Thanks! Erik


回答1:


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.




回答2:


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 :)



来源:https://stackoverflow.com/questions/26544314/using-uiimageview-together-with-constraints

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!