[iOS] Label 自适应高度与长度

自适应高度:

//首先要设置一个属性,赋给label可显示的最大行数, 0 表示不限制行数
self.label.numberOfLines = 0;

+ (CGFloat)heightForLabel:(NSString *)text{

    CGRect rect = [text boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width - 85 * WIDTH, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont fontWithName:@"ArialUnicodeMS" size:17.1]} context:nil];

    return rect.size.height;
}

自适应长度:

// 任意给个初始尺寸, 后面会重新赋值尺寸
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
[self.view addSubview:label];
NSString *text = @"**** **** **** 1234";
label.text = text;

CGSize size = [text sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:17.0]}];
// ceilf()向上取整函数, 只要大于1就取整数2. floor()向下取整函数, 只要小于2就取整数1.
CGSize size = CGSizeMake(ceilf(size.width), ceilf(size.height));
label.frame = CGRectMake(0, 0, size.width, size.height);

推荐阅读更多精彩内容