iOS:多行UILabel在自动布局 [英] iOS: Multi-line UILabel in Auto Layout

查看:656
本文介绍了iOS:多行UILabel在自动布局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法使用自动布局实现一些非常基本的布局行为。我的视图控制器在IB中如下所示:

I'm having trouble trying to achieve some very basic layout behavior with Auto Layout. My view controller looks like this in IB:

顶部标签是标题标签,我不知道它会有多少行。我需要标题标签来显示所有文本行。我还需要另外两个标签和小图像放置在标题下方,不管它是多么高。我已经设置了标签和小图像之间的垂直间距约束,以及标题标签和其超级视图之间的顶部间距约束以及小图像和其超级视图之间的底部间距约束。白色UIView没有高度约束,因此它应该垂直伸展以包含其子视图。我已将标题标签的行数设置为0.

The top label is the title label, I don't know how many lines it will be. I need the title label to display all lines of text. I also need the other two labels and the small image to be laid out right below the title, however tall it happens to be. I have set vertical spacing constraints between the labels and small image, as well as a top spacing constraint between the title label and its superview and a bottom spacing constraint between the small image and its superview. The white UIView has no height constraint, so it should stretch vertically to contain its subviews. I have set the number of lines for the title label to 0.

如何获得标题标签以调整大小以适应字符串所需的行数?我的理解是,我不能使用setFrame方法,因为我使用自动布局。我必须使用自动布局,因为我需要那些其他的意见,留在标题标签(因此的约束)。

How can I get the title label to resize to fit the number of lines required by the string? My understanding is that I can't use setFrame methods because I'm using Auto Layout. And I have to use Auto Layout because I need those other views to stay below the title label (hence the constraints).

我如何做到这一点?

推荐答案

上使用 -setPreferredMaxLayoutWidth 和autolayout应该处理剩余的。

Use -setPreferredMaxLayoutWidth on the UILabel and autolayout should handle the rest.

[label setPreferredMaxLayoutWidth:200.0];

请参阅 UILabel文档

UPDATE:

只需要将storyboard中的高度约束设置为大于或等于,不需要setPreferredMaxLayoutWidth。

Only need to set the height constraint in storyboard to Greater than or equal to", no need to setPreferredMaxLayoutWidth.

这篇关于iOS:多行UILabel在自动布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆