一、自適應(yīng)高度
//首先要設(shè)置一個屬性,賦給label可顯示的最大行數(shù), 0 表示不限制行數(shù)
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;
}
二仅父、自適應(yīng)寬度
// 任意給個初始尺寸, 后面會重新賦值尺寸
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()向上取整函數(shù), 只要大于1就取整數(shù)2. floor()向下取整函數(shù), 只要小于2就取整數(shù)1.
CGSize size = CGSizeMake(ceilf(size.width), ceilf(size.height));
label.frame = CGRectMake(0, 0, size.width, size.height);