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的高度
// 結構體賦值 (不能直接賦值 要用中間變量轉化)(直接賦值會導致系統把 點語法 與 frame (結構體) 的點 混用)
CGRect temp = label.frame;
temp.size.height = frame.size.height ;
label.frame = temp;