宽度定死、按照行间距、字体算出label高度

方法如下

- (CGFloat)heightWithFont:(UIFont *)font constrainedToWidth:(CGFloat)width lineSpacing:(CGFloat)spacing
{
    UIFont *textFont = font ? font : [UIFont systemFontOfSize:[UIFont systemFontSize]];
    CGSize textSize;
    // 这里只支持>=ios8
    NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
    paragraph.lineSpacing = spacing;
    paragraph.lineBreakMode = NSLineBreakByWordWrapping;
    NSDictionary *attributes = @{NSFontAttributeName: textFont,
                             NSParagraphStyleAttributeName: paragraph};
    textSize = [self boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX)
                              options:(NSStringDrawingUsesLineFragmentOrigin |
                                       NSStringDrawingTruncatesLastVisibleLine)
                           attributes:attributes
                              context:nil].size;
    return ceil(textSize.height);
}
posted @ 2017-05-18 16:56  张驰小方块  阅读(211)  评论(0编辑  收藏  举报