假设我在UILabel中有以下文本(一长行动态文本):

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

我想调整UILabel的高度,这样文本就可以放进去了。我使用以下属性的UILabel,使文本内包装。

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

如果我的方向不对,请告诉我。谢谢。


当前回答

问题是,没有提到的函数是可靠的,一些字符串和字体将返回不正确的高度值。尤其是带属性的文本。

唯一可行的解决方案是:https://stackoverflow.com/a/4214978/699944,重点是使用CoreText手动计算每一行的高度,以获得正确的大小。没有其他已知的方法可以做到这一点。

其他回答

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;

您可以在设计时在Storyboard/XIB中这样做,而不是通过编程来完成。

在属性检查器中将UIlabel的行数属性设置为0。 然后根据需要设置宽度约束/(或)前导和后导约束。 然后用最小值设置高度约束。最后选择你添加的高度约束,在大小检查器属性检查器旁边,改变高度约束的关系从等于-大于。

当自动布局被启用时,调整大小不工作:)

UILabel *itemTitle = [[UILabel alloc] initWithFrame:CGRectMake(10.0f, 10,100, 200.0f)];
itemTitle.text = @"aseruy56uiytitfesh";
itemTitle.adjustsFontSizeToFitWidth = NO;
itemTitle.autoresizingMask = UIViewAutoresizingFlexibleWidth;
itemTitle.font = [UIFont boldSystemFontOfSize:18.0];
itemTitle.textColor = [UIColor blackColor];
itemTitle.shadowColor = [UIColor whiteColor];
itemTitle.shadowOffset = CGSizeMake(0, 1);
itemTitle.backgroundColor = [UIColor blueColor];
itemTitle.lineBreakMode = UILineBreakModeWordWrap;
itemTitle.numberOfLines = 0;
[itemTitle sizeToFit];
[self.view addSubview:itemTitle];

使用这里所有的属性都使用在标签上,并通过增加itemTitle中的文本来测试它。文本

itemTitle.text = @"diofgorigjveghnhkvjteinughntivugenvitugnvkejrfgnvkhv";

它会根据你的需要给出完美的答案

谢谢你写这篇文章。这对我帮助很大。在我的例子中,我也在一个单独的视图控制器中编辑文本。我注意到当我使用:

[cell.contentView addSubview:cellLabel];

在tableView:cellForRowAtIndexPath:方法中,每当我编辑单元格时,标签视图不断地在前一个视图之上呈现。文本变得像素化,当某些内容被删除或更改时,旧版本在新版本下可见。下面是我解决这个问题的方法:

if ([[cell.contentView subviews] count] > 0) {
    UIView *test = [[cell.contentView subviews] objectAtIndex:0];
    [test removeFromSuperview];
}
[cell.contentView insertSubview:cellLabel atIndex:0];

不再有奇怪的分层。如果有更好的处理方法,请告诉我。