在我的特殊情况下,我在视图控制器中有视图,我为其添加了以下约束:
In my particular case I have view inside the view controller for which I added the following constraints:
现在视图位于视图控制器的上半部分.
Now the view sits in the top half on the view controller.
在其中我添加了一个方形图像视图,为此我添加了以下约束:
Inside this I add a square image view, for which I added the following constraints:
我的约束看起来很完美,但是在模拟器中运行时,我没有得到一个完美的正方形.除此之外,在不同的模拟器屏幕上运行时,图像视图不会调整大小.
My constraints seems perfect, but when running in the simulator I don't get a perfect square. Besides this, the image view doesn't get resize when running on different simulator screens.
这是我的设置:
我查看了其他 stackoverflow 帖子,但似乎没有任何效果.
I looked on other stackoverflow posts, but nothing seems to work.
是否有一些基本步骤可以做到这一点?
Are there some basic steps to do this ?
设置>=10个约束后:
After setting >=10 constraints:
我添加了顶部,底部,前导,尾随约束2次,1次小于或等于(优先级1000),另一个大于或等于(优先级800),常数值为90.我不知道为什么底部它试图从主视图延伸到 90 pt,而不是容器视图(绿色).
edit 3: I added top,bottom,leading,trailing constraints 2 times, 1 with lower than or equal(priority 1000), the other one with greater than or equal(priority 800) with the constant value of 90. I don't know why for bottom it tries to streches to 90 pt from the main view, not the container view(green one).
您有一个视图需要扩展以填充其容器,同时保持其纵横比.这是 Auto Layout 的常见模式.
You have a view that needs to expand to fill its container while maintaining its aspect ratio. This is a common pattern with Auto Layout.
诀窍是对前导/尾随/顶部/底部使用两个约束:
The trick is to use two constraints for leading/trailing/top/bottom:
=10
低优先级
>=10
在所需的优先级.
综合起来,你有:
宽高比 1:1
Aspect Ratio 1:1
在 Superview 中居中 X/Y
Center X/Y in Superview
前导/尾随/顶部/底部到超级视图 = 10(优先级为 750)
Leading/Trailing/Top/Bottom to Superview = 10 (at 750 priority)
前导/尾随/顶部/底部到 Superview >= 10(优先级为 1000)
Leading/Trailing/Top/Bottom to Superview >= 10 (at 1000 priority)
UIImageView 还需要考虑一些事项:
There are also a couple of things to consider with UIImageView:
UIImageView 将根据其显示的图像具有固有的内容大小,因此您需要确保其 Content Hugging Priority 低于您用于 =10<的 750 优先级/code> 约束.
UIImageView will have an intrinsic content size based on the image that it is displaying, so you'll want to ensure that its Content Hugging Priority is lower than the 750 priority you use for the =10
constraints.
UIImageView.contentMode
确定基础图像的大小相对于 UIImageView 的大小.默认情况下,它设置为 UIViewContentModeScaleToFill
.
UIImageView.contentMode
determines how the underlying image is sized relative to the size of the UIImageView. By default, it's set to UIViewContentModeScaleToFill
.
这篇关于如何使用自动布局使用其超级视图调整方形视图的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!