31

在界面构建器中,我们可以固定高度,固定宽度,使两个视图宽度相等,但是我如何设置约束,以便在调整视图大小时,它保持其宽度/高度比?

在我的特殊情况下,我的视图控制器中有一个 UIImageView 。当视图调整大小时,我希望我的图像视图调整大小,但保持 3:2 的宽度:高度比。是否可以在 IB 中完成?有没有可能用代码做到这一点?

谢谢!

4

3 回答 3

36

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

于 2014-03-15T16:40:09.900 回答
34

我不认为你可以在 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]];

这明确地将高度设置为 100,将宽高比设置为 3:2。

于 2013-01-07T00:30:50.923 回答
0

Apple 的这份指南对我很有帮助——它概述了两种方法,一种是关闭某些子视图的 AutoLayout 并直接设置框架,另一种是通过代码使用纯 AutoLayout。

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

于 2015-05-01T18:39:50.953 回答