Label的自适应高度
创建一个label
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 300, 100)];
label.numberOfLines = 0;
label.font = [UIFont systemFontOfSize:16];
label.backgroundColor = [UIColor grayColor];
NSString *str = @" -- --- - -- -- -- -- -- -- ---....... ";
label.text = str;
[self.window addSubview:label];
[label release];
自适应高度思路
计算字符串的所占高度
定值:宽度 字体大小
参数size : 宽度 与 label的宽度一样
构建字体大小的字典
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:16], NSFontAttributeName, nil];
求出自适应高度
// CGFLOAT_MAX最大浮点数
CGRect frame = [str boundingRectWithSize:CGSizeMake(300, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
NSLog(@"%f",frame.size.height);
// 更改label的高度
// 结构体赋值
CGRect temp = label.frame;
temp.size.height = frame.size.height ;
label.frame = temp;