在iOS开发中我们都会遇到界面搭建中UILabel文本的宽度和高度的不可预估带来的适配或者约束中的麻烦。
1.单行
计算单行文本较为简单,我尽量写的详细一些。
//1.创建UILabel但不要设置frame
UILabel *text = [[UILabel alloc]init];
//2.给字符串
text.text = @"Hello World!";
//3.设置UIFont
text.font = [UIFont systemFontOfSize:14];
//4.根据text的font和字符串自动算出size(重点)
CGSize size = [text.text sizeWithAttributes:@{NSFontAttributeName:text.font}];
//5.根据size设置frame
text.frame = CGRectMake(100, 100, size.width, size.height);
//设置背景让我们看一下大小效果
text.backgroundColor = [UIColor grayColor];
运行效果:
2.多行
计算多行文本就会比较麻烦了。
//1.创建UILabel但不要设置frame
UILabel *text = [[UILabel alloc]init];
//2.给多行字符串
text.text = @"Hello World!Hello World!Hello World!Hello World!Hello World!";
//3.设置自动换行
text.numberOfLines = 0;
//4.设置UIFont
text.font = [UIFont systemFontOfSize:14];
/**
5.根据text的font和字符串自动算出size(重点)
200:你希望的最大宽度
MAXFLOAT:最大高度为最大浮点数
**/
CGSize size = [text.text boundingRectWithSize:CGSizeMake(200, MAXFLOAT)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName:text.font}
context:nil].size;
//6.根据size设置frame
text.frame = CGRectMake(100, 100, size.width, size.height);
//设置背景让我们看一下大小效果
text.backgroundColor = [UIColor grayColor];
运行效果: