自适应label的高度

时间:2022-04-22 00:49:27

iOS7以下的系统可使用方法

//获得当前cell高度

CGRect frame = [self frame];

//文本赋值

self.introduction.text = text;

//设置label的最大行数

self.introduction.numberOfLines = 0;

CGSize size = CGSizeMake(300, 1000);

CGSize labelSize = [self.introduction.text sizeWithFont:self.introduction.font constrainedToSize:size lineBreakMode:NSLineBreakByClipping];

NSLog(@"w = %f", labelSize.width);

NSLog(@"h = %f", labelSize.height);

iOS7以上才支持的方法

//    NSAttributedString *attrStr = [[NSAttributedString alloc] initWithString:self.introduction.text];

////    self.introduction.attributedText = attrStr;

//    NSRange range = NSMakeRange(0, attrStr.length);

//    NSDictionary *dic = [attrStr attributesAtIndex:0 effectiveRange:&range];

NSDictionary *dic = @{NSFontAttributeName: self.introduction.font};

CGSize labelSize1 = [self.introduction.text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:dic context:nil].size;

NSLog(@"w = %f", labelSize1.width);

NSLog(@"h = %f", labelSize1.height);

self.introduction.frame = CGRectMake(self.introduction.frame.origin.x, self.introduction.frame.origin.y, labelSize1.width, labelSize1.height);

//计算出自适应的高度

frame.size.height = labelSize1.height+100;

self.frame = frame;

iOS6以上才支持的方法

NSAttributedString *str = [[NSAttributedString alloc] initWithString:self.introduction.text];

NSAttributedString *str1 = [[NSAttributedString alloc] initWithString:self.introduction.text attributes:@{NSFontAttributeName : self.introduction.font}];

CGSize size1 = [str boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil].size;

CGSize size2 = [str1 boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil].size;