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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14188187/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 21:44:30  来源:igfitidea点击:

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

iosxcodeautolayout

提问by Joseph Lin

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. When the view resizes, I'd like my image view to resize, but maintain a 3:2 width:height ratio. Is it possible to do it in IB? Is it possible to do it with code?

在我的特殊情况下,我的视图控制器中有一个 UIImageView。当视图调整大小时,我希望我的图像视图调整大小,但保持 3:2 的宽高比。IB可以做吗?可以用代码来做吗?

Thanks!

谢谢!

回答by rudi

You can add an aspect ratio constraint in IB by control dragging from the view to itself and choosing aspect ratio.

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

回答by rdelmar

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。

回答by Dave Cole

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