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

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

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

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

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


当前回答

基于Swift 4及以上答案的UILabel扩展

extension UILabel {

    func retrieveTextHeight () -> CGFloat {
        let attributedText = NSAttributedString(string: self.text!, attributes: [NSFontAttributeName:self.font])

        let rect = attributedText.boundingRect(with: CGSize(width: self.frame.size.width, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, context: nil)

        return ceil(rect.size.height)
    }

}

可以这样使用:

self.labelHeightConstraint.constant = self.label.retrieveTextHeight()

其他回答

更新方法

+ (CGFloat)heightForText:(NSString*)text font:(UIFont*)font withinWidth:(CGFloat)width {

    CGSize constraint = CGSizeMake(width, 20000.0f);
    CGSize size;

    CGSize boundingBox = [text boundingRectWithSize:constraint
                                                  options:NSStringDrawingUsesLineFragmentOrigin
                                               attributes:@{NSFontAttributeName:font}
                                                  context:nil].size;

    size = CGSizeMake(ceil(boundingBox.width), ceil(boundingBox.height));

    return size.height;
}

这是使用Objective-c获取UILabel Height的一行代码:

labelObj.numberOfLines = 0;
CGSize neededSize = [labelObj sizeThatFits:CGSizeMake(screenWidth, CGFLOAT_MAX)];

使用.height你会得到标签的高度,如下所示:

neededSize.height

根据iOS7更新

// If description are available for protocol
protocolDescriptionLabel.text = [dataDictionary objectForKey:@"description"];
[protocolDescriptionLabel sizeToFit];
[protocolDescriptionLabel setLineBreakMode:NSLineBreakByWordWrapping];

CGSize expectedLabelSize = [protocolDescriptionLabel
               textRectForBounds:protocolDescriptionLabel.frame
               limitedToNumberOfLines:protocolDescriptionLabel.numberOfLines].size;
NSLog(@"expectedLabelSize %f", expectedLabelSize.height);

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

在iOS 6中,苹果为UILabel添加了一个属性,极大地简化了标签的动态垂直大小调整:preferredmaxlayoutidth。

将此属性与lineBreakMode = nslinebreakbywordwrapped和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];
...

谢谢大家的帮助,这是我尝试的代码,这是为我工作

   UILabel *instructions = [[UILabel alloc]initWithFrame:CGRectMake(10, 225, 300, 180)];
   NSString *text = @"First take clear picture and then try to zoom in to fit the ";
   instructions.text = text;
   instructions.textAlignment = UITextAlignmentCenter;
   instructions.lineBreakMode = NSLineBreakByWordWrapping;
   [instructions setTextColor:[UIColor grayColor]];

   CGSize expectedLabelSize = [text sizeWithFont:instructions.font 
                                constrainedToSize:instructions.frame.size
                                    lineBreakMode:UILineBreakModeWordWrap];

    CGRect newFrame = instructions.frame;
    newFrame.size.height = expectedLabelSize.height;
    instructions.frame = newFrame;
    instructions.numberOfLines = 0;
    [instructions sizeToFit];
    [self addSubview:instructions];