UILabel 调整行间距

Posted brucemengbm

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了UILabel 调整行间距相关的知识,希望对你有一定的参考价值。

/*
 调整行间距
 */
+ (void)adjustLineSpacingOfLabel:(UILabel *)label to:(CGFloat)lineSpacing
{
    NSString *textStr = label.text;
    if (textStr.length <= 0) {
        return;
    }
    
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:textStr];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:lineSpacing];
    [paragraphStyle setLineBreakMode:NSLineBreakByTruncatingTail];
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [textStr length])];
    label.attributedText = attributedString;
    [label sizeToFit];
}

+ (CGSize)sizeOfMultiLineLabel:(NSString *)aLabelTextString font:(UIFont *)aLabelFont constrainedToSize:(CGSize)maxSize lineSpacing:(CGFloat)lineSpacing
{
    if ([[[UIDevice currentDevice] systemVersion] floatValue] < 7.0) {
        //version < 7.0
        return [aLabelTextString sizeWithFont:aLabelFont
                            constrainedToSize:maxSize
                                lineBreakMode:NSLineBreakByTruncatingTail];
    }
    else if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
        //version >= 7.0
        //Return the calculated size of the Label
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        [paragraphStyle setLineSpacing:lineSpacing];
        [paragraphStyle setLineBreakMode:NSLineBreakByWordWrapping];
        
        return [aLabelTextString boundingRectWithSize:maxSize
                                              options:NSStringDrawingUsesLineFragmentOrigin
                                           attributes:@{NSFontAttributeName:aLabelFont, NSParagraphStyleAttributeName:paragraphStyle}
                                              context:nil].size;
    }
    return CGSizeZero;
}


以上是关于UILabel 调整行间距的主要内容,如果未能解决你的问题,请参考以下文章

UILabel 调整行间距

调整label的行间距、字间距

iOS UILabel 设置行高

iOS UILabel 设置行高

Label设置行间距--b

(转)iOS学习——UIlabel设置行间距和字间距