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;
}


posted on 2016-01-29 17:21  封起De日子  阅读(184)  评论(0编辑  收藏  举报

导航