使用自动布局,如何根据图像动态调整 UIImageView 的大小? [英] With Auto Layout, how do I make a UIImageView's size dynamic depending on the image?

查看:34
本文介绍了使用自动布局,如何根据图像动态调整 UIImageView 的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的 UIImageView 根据它显示的实际图像的大小来增长或缩小.但我希望它保持垂直居中,并且距离超级视图的前缘 10pts.

I want my UIImageView to grow or shrink depending on the size of what the actual image it's displaying is. But I want it to stay vertically centered and 10pts from the leading edge of the superview.

然而,如果我设置这两个约束,它会抱怨我没有设置足够的约束来满足自动布局.对我来说,它似乎完美地描述了我想要的东西.我错过了什么?

However, if I set these two constraints it complains I haven't set up enough constraints to satisfy Auto Layout. To me it seems to perfectly describe what I want. What am I missing?

推荐答案

图像视图的固有大小已经依赖于图像的大小.您的假设(和约束是正确的).

The image view's intrinsic size is already dependent on the size of the image. Your assumptions (and constraints are correct).

然而,如果你已经在界面构建器中设置了你的图像视图并且没有为它提供图像,那么布局系统(界面构建器)将不知道你的图像视图在编译时应该有多大.您的布局不明确,因为您的图像视图可能有多种尺寸.这就是引发错误的原因.

However, if you've set up your image view in interface builder and have not provided it with an image, then the layout system (interface builder) won't know how big your image view is supposed to be at compile time. Your layout is ambiguous because your image view could be many sizes. This is what throws the errors.

一旦你设置了图像视图的图像属性,图像视图的内在尺寸就由图像的尺寸定义.如果您在运行时设置视图,那么您可以完全按照 Anna 所说的去做,并在图像视图的属性检查器中为界面构建器提供占位符"固有大小.这告诉界面构建器,现在使用这个尺寸,稍后我会给你一个真实的尺寸".占位符约束在运行时被忽略.

Once you set your image view's image property, then the image view's intrinsic size is defined by the size of the image. If you're setting the view at runtime, then you can do exactly what Anna mentioned and provide interface builder with a "placeholder" intrinsic size in the property inspector of the image view. This tells interface builder, "use this size for now, I'll give you a real size later". The placeholder constraints are ignored at runtime.

您的另一个选择是直接将图像分配给界面构建器中的图像视图(但我假设您的图像是动态的,因此这对您不起作用).

Your other option is to assign the image to the image view in interface builder directly (but I assume your images are dynamic, so this won't work for you).

这篇关于使用自动布局,如何根据图像动态调整 UIImageView 的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆