计算UILabel的size


_label.text = @"自动计算长度";
_label.font = [UIFont systemFontOfSize:12.0f];
    CGSize size = [self sizeForString:_label.text attribute:@{NSFontAttributeName:_label.font} width:MAXFLOAT];
    _label.frame = CGRectMake(0, 0, size.width, size.height);


#pragma mark - tool
-(CGSize) sizeForString:(NSString*)string attribute:(NSDictionary*) attribute width:(CGFloat)width
{
    CGRect newFrame = [string boundingRectWithSize:CGSizeMake(width, MAXFLOAT)
                                           options:NSStringDrawingUsesLineFragmentOrigin
                                        attributes:attribute
                                           context:nil];
    newFrame.size.height = ceil(newFrame.size.height);
    return newFrame.size;
}

以上代码就是自动计算UILabel需要的size,通常会限制width,计算至少需要多height.
attribute:这是限定条件,根据实际情况来填写;

你可能感兴趣的:(UILabel)