How to scale a UIImage view to a square with Autolayout inside a UIScrollView

泪湿孤枕 提交于 2019-12-13 02:18:11

问题


I've been struggling to learn autolayout (finally). I want to have a vertically scrolling UIScrollView that holds all the content for the view. I want to pin a UIImage view to the top of the scrollview and keep the image a square (scaleToFill). Basically I want to do this (only I want to do it with autolayout):

I can't get the image to keep its aspect ratio while staying within the screen bounds. Whenever I add an aspect ratio constraint the imageView grows to like 600 points (the width of the png I think), but I want it to just be as wide as the screen.

I think I am setting the constraints up for the UIImageView correctly because if I get rid of the scrollView and just drop the imageViw directly on the view then it seems to do what I want it to. The trick is putting it inside the scrollView.

This is how I currently have it set up:

The 4 vertical/horizontal space constraints on the scroll view are all set to constant 0.


回答1:


Since the size of the UIScrollView depends on its content, you cannot have the size of your UIImageView subview dependent on it.

You have to remove the aspect ratio constraint of the UIImageView and use a fixed width one. You can also have your UIImageView width dependent on another view in the UIScrollView which has either a fixed width or otherwise unambiguous width.

Don't forget to use Placeholder as the intrinsic size value in Interface Builder.

Hope this helps.



来源:https://stackoverflow.com/questions/25773527/how-to-scale-a-uiimage-view-to-a-square-with-autolayout-inside-a-uiscrollview

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