計算 NSMutableAttributedString 高度,必須要有兩個屬性
-(void)test{ UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(50, 50, 300, 300)]; label.backgroundColor = [UIColor redColor]; //可分行
label.numberOfLines = 0; NSString *str = @"修改數據很明顯是屬於 model 層的任務。Model 應該為諸如刪除或重新排序等操作暴露一個 API,然后我們可以在 data source 方法中調用它。這樣,controller 就可以扮演 view 和 model 之間的協調者,而不需要知道 model 層的實現細節。並且還有額外的好處,model 的邏輯也變得更容易測試,因為它不再和 view controllers 的任務混雜在一起了"; //屬性可變的 string
NSMutableAttributedString *str1 = [[NSMutableAttributedString alloc]initWithString:str]; //可變的范圍
NSRange range = {0,[str1 length]}; //范圍內的字加下划線
[str1 addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:range]; [str1 addAttribute:NSFontAttributeName value:label.font range:range]; //范圍內的字體顏色為綠色
[str1 addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(0, 20)]; //計算 string 的高度
CGSize attSize = [str1 boundingRectWithSize:CGSizeMake(300, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil].size; label.attributedText = str1; label.frame = CGRectMake(50, 50, attSize.width, attSize.height); [self.view addSubview:label]; }