根据文字调整UILabel的高度

考虑一下,我在UILabel (一长串动态文本)中有以下文本:

由于外星人军队远远超过了队伍,玩家必须利用后世界末日的世界来获得他们的优势,比如在垃圾箱,柱子,汽车,瓦砾和其他物体后面寻找掩体。

我想调整UILabel's高度,以便文本可以适应。我使用UILabel以下属性来使文本内容包装。

myUILabel.lineBreakMode = UILineBreakModeWordWrap;
myUILabel.numberOfLines = 0;

如果我没有朝着正确的方向前进,请告诉我。 谢谢。


sizeWithFont constrainedToSize:lineBreakMode:是要使用的方法。 如何使用它的一个例子如下:

//Calculate the expected size based on the font and linebreak mode of your label
// FLT_MAX here simply means no constraint in height
CGSize maximumLabelSize = CGSizeMake(296, FLT_MAX);

CGSize expectedLabelSize = [yourString sizeWithFont:yourLabel.font constrainedToSize:maximumLabelSize lineBreakMode:yourLabel.lineBreakMode];   

//adjust the label the the new height.
CGRect newFrame = yourLabel.frame;
newFrame.size.height = expectedLabelSize.height;
yourLabel.frame = newFrame;

你正朝着正确的方向前进。 你所需要做的就是:

myUILabel.numberOfLines = 0;
myUILabel.text = @"Enter large amount of text here";
[myUILabel sizeToFit];

在iOS 6中,Apple向UILabel添加了一个属性,该属性极大地简化了标签的动态垂直调整大小: preferredMaxLayoutWidth

通过将此属性与lineBreakMode = NSLineBreakByWordWrapping和sizeToFit方法结合使用,可以轻松地将UILabel实例的大小调整为适应整个文本的高度。

来自iOS文档的引用:

preferredMaxLayoutWidth多行标签的首选最大宽度(以磅为单位)。

讨论当对其应用布局约束时,此属性会影响标签的大小。 在布局过程中,如果文本超出了此属性指定的宽度,则附加文本会流向一个或多个新行,从而增加标签的高度。

一个样品:

...
UILabel *status = [[UILabel alloc] init];
status.lineBreakMode = NSLineBreakByWordWrapping;
status.numberOfLines = 5; // limits to 5 lines; use 0 for unlimited.

[self addSubview:status]; // self here is the parent view

status.preferredMaxLayoutWidth = self.frame.size.width; // assumes the parent view has its frame already set.

status.text = @"Some quite lengthy message may go here…";
[status sizeToFit];
[status setNeedsDisplay];
...
链接地址: http://www.djcxy.com/p/4829.html

上一篇: Adjust UILabel height depending on the text

下一篇: Textview Center Text Alignment IOS 7