简体   繁体   English

自动布局约束:如何在调整大小时使视图保持其宽高比?

[英]Auto-Layout Constraint: How to make a view maintains its width/height ratio when resized?

In the interface builder we can pin height, pin width, make two views width equally, but how do I set the constraints so that when a view is being resized, it maintains its width/height ratio? 在界面构建器中,我们可以固定高度,引脚宽度,使两个视图宽度相等,但是如何设置约束,以便在调整视图大小时,它保持宽度/高度比?

In my particular case, I have an UIImageView in my view controller. 在我的特定情况下,我的视图控制器中有一个UIImageView。 When the view resizes, I'd like my image view to resize, but maintain a 3:2 width:height ratio. 当视图调整大小时,我希望我的图像视图调整大小,但保持3:2的宽度:高度比。 Is it possible to do it in IB? 在IB中可以做到吗? Is it possible to do it with code? 是否可以使用代码执行此操作?

Thanks! 谢谢!

您可以通过控制从视图拖动到自身并选择纵横比来在IB中添加纵横比约束。

I don't think you can do that in IB, but in code, it can be done like this (iv is my outlet to the image view): 我不认为你可以在IB中做到这一点,但在代码中,它可以这样做(iv是我的图像视图的出口):

    [self.iv removeConstraints:self.iv.constraints];
    NSLayoutConstraint *con1 = [NSLayoutConstraint constraintWithItem:self.iv attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1  constant:100];
    NSLayoutConstraint *con2 = [NSLayoutConstraint constraintWithItem:self.iv attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self.iv attribute:NSLayoutAttributeWidth multiplier:.66 constant:0];
    [self.iv addConstraints:@[con1,con2]];

This explicitly sets the height to 100, and the width to height ratio to 3:2. 这明确地将高度设置为100,并将宽高比设置为3:2。

This guide from Apple really helped me - it outlines two approaches, one where you turn off AutoLayout for certain subviews and set frames directly, and another where you use pure AutoLayout via code. Apple的这个指南真的帮助了我 - 它概述了两种方法,一种是关闭某些子视图的AutoLayout并直接设置框架,另一种是通过代码使用纯AutoLayout的方法。

https://developer.apple.com/library/ios/technotes/tn2154/_index.html https://developer.apple.com/library/ios/technotes/tn2154/_index.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM