以编程方式自动布局和 UIImageView

Posted

技术标签:

【中文标题】以编程方式自动布局和 UIImageView【英文标题】:Autolayout programmatically and UIImageView 【发布时间】:2015-09-01 09:09:13 【问题描述】:

我正在尝试在代码中布局一些视图。在运行时,我需要检查我们有多少交易,然后适当地布局代码。我有一个 UILabel 和一个 UIImageView。

我按如下方式创建对象:

UILabel *numberOfDealsLabel = [UILabel new];
[numberOfDealsLabel setFont:[UIFont fontWithName:@"HelveticaNeue-CondensedBold" size:50]];
numberOfDealsLabel.translatesAutoresizingMaskIntoConstraints = NO;
numberOfDealsLabel.textColor = [UIColor whiteColor];
[numberOfDealsLabel setTextAlignment:NSTextAlignmentCenter];
numberOfDealsLabel.numberOfLines = 1;
numberOfDealsLabel.text = [NSString stringWithFormat:@"%d", 2];
[numberOfDealsLabel sizeToFit];
numberOfDealsLabel.preferredMaxLayoutWidth = view.frame.size.width;
[view addSubview:numberOfDealsLabel];

UIImageView *dealsImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"deal"]];
[view addSubview:dealsImage];

视图只是一个正方形。从这里我尝试添加以下约束,以便两个视图都紧贴视图顶部并水平共享空间。

[view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[numberOfDealsLabel][dealsImage]|" options:nil metrics:nil views:views]];

[view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[numberOfDealsLabel]|" options:nil metrics:nil views:views]];

[view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[dealsImage]|" options:nil metrics:nil views:views]];

我收到以下错误:

可能至少以下列表中的一个约束是您不想要的。试试这个:(1)查看每个约束并尝试找出您不期望的; (2) 找到添加了一个或多个不需要的约束的代码并修复它。 (注意:如果您看到不理解的 NSAutoresizingMaskLayoutConstraints,请参阅 UIView 属性 translatesAutoresizingMaskIntoConstraints 的文档)

此错误是由以下约束引起的:

[查看 addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[numberOfDealsLabel][dealsImage]|"选项:无指标:无视图:视图]];

我不明白为什么这会导致问题。我的第一个想法是因为 UILabel 太大了,加上图像的大小导致了问题。但是,我将文本大小更改为非常小的数字,但我仍然遇到同样的问题。

任何关于可能导致此问题的建议都会很棒。

【问题讨论】:

【参考方案1】:

从外观上看,您没有在 UIIamgeView 上调用“translatesAutoresizingMaskIntoConstraints = NO”,如果不能解决整个问题,这至少应该有所帮助

所以,如果我是你,这是我要做的第一件事:

UIImageView *dealsImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"deal"]];
[dealsImage setTranslatesAutoresizingMaskIntoConstraints:FALSE]; //this is new code
[view addSubview:dealsImage];

来自苹果:

对于知道自动布局的视图,在大多数情况下,您 希望 translatesAutoresizingMaskIntoConstraints 为 NO。

https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/AutolayoutPG/AdoptingAutoLayout/AdoptingAutoLayout.html

【讨论】:

这正是问题所在。我为 UILabel 设置了它,但没有为 imageView 设置它。谢谢。

以上是关于以编程方式自动布局和 UIImageView的主要内容,如果未能解决你的问题,请参考以下文章

UIImageView .scaleAspectFit 和自动布局不能从 Swift 以编程方式工作

WKWebview & UIImageView 在 UIScrollView 内以编程方式自动布局 Objective-C

iOS - 以编程方式在具有自动布局的 UITextField 内定位 UIImageView

如何以编程方式更改使用自动布局在情节提要上创建的 UIImageView 的大小?

以编程方式自动布局不起作用

使用自动布局的屏幕外 UIView(以编程方式)