iOS常用

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

2020-06-02  本文已影响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;
}
上一篇下一篇

猜你喜欢

热点阅读