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;