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

查看:35
本文介绍了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).

我怎样才能做到这一点?

How can I make this happen?

推荐答案

UILabel 上使用 -setPreferredMaxLayoutWidth 并且自动布局应该处理其余的.

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

[label setPreferredMaxLayoutWidth:200.0];

请参阅 UILabel 有关 preferredMaxLayoutWidth 的文档.

更新:

只需将storyboard中的height约束设置为Greater than or equal to,无需设置PreferredMaxLayoutWidth.

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

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

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