美文网首页iOS常用
iOS-UILabel扩展类方法(计算UILabel宽度,高度)

iOS-UILabel扩展类方法(计算UILabel宽度,高度)

作者: 贵叔勇闯天涯 | 来源:发表于2020-06-02 14:43 被阅读0次

1、计算UILabel占用的Size

+ (CGSize)wsg_estimateSizeOfText:(NSString *)text withMaxWidth:(CGFloat)maxWidth font:(UIFont *)font LineSpace:(CGFloat)lineSpace {
    NSMutableDictionary *attrDic = [NSMutableDictionary new];
    attrDic[NSFontAttributeName] = font;
    if (lineSpace > 0) {
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        [paragraphStyle setLineSpacing:lineSpace];
        attrDic[NSParagraphStyleAttributeName] = paragraphStyle;
    }
    CGSize labelSize = [text boundingRectWithSize:CGSizeMake(maxWidth, MAXFLOAT)
                                          options:NSStringDrawingUsesLineFragmentOrigin
                                       attributes:attrDic
                                          context:nil].size;
    return labelSize;
}

2、动态修改UILabel的行高

- (void)wsg_setTextLineSpacing:(NSString*)text lineSpacing:(CGFloat)lineSpacing {
    if (!text || lineSpacing < 0.01) {
        self.text = text;
        return;
    }
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:lineSpacing];        //设置行间距
    [paragraphStyle setLineBreakMode:self.lineBreakMode];
    [paragraphStyle setAlignment:self.textAlignment];
    
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:text];
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [text length])];
    self.attributedText = attributedString;
}

相关文章

网友评论

    本文标题:iOS-UILabel扩展类方法(计算UILabel宽度,高度)

    本文链接:https://www.haomeiwen.com/subject/odlnohtx.html