標籤:des style blog io ar color os sp for
當 UITableView 中有一個 label 的內容比較長的時候,就需要 cell 自適應高度來多行展示label;
首先設定 label 的 line 為0;
代碼如下:
// 為每一個 cell 預設定一個高度,可以提高效率- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath { return 44;}// 這裡每一個 cell 的實際高度(即自適應高度)- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { // 這裡可以通過 if 判斷語句來為你需要的那一行單獨設定自適應高度 if (indexPath.row == [rowsArr count] - 1) { // 通過資料來擷取 label 所需要的高度 NSString *rowName = [rowsArr objectAtIndex:indexPath.row]; NSString *key = [rowsAndKeyDic objectForKey:rowName]; CGFloat descriptionH = [self textHeight:[taskDetailDic objectForKey:key]]; return descriptionH + 20;// 這個70 完全是根據你的情況調整的 } return 44;}// 擷取 label 實際所需要的高度- (CGFloat)textHeight:(NSString *)labelText { UIFont *tfont = [UIFont systemFontOfSize:16.0]; NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:tfont,NSFontAttributeName,nil]; // ios7 的API,判斷 labelText 這個字串需要的高度; 這裡的寬度(self.view.frame.size.width - 140he)按照需要自己換就 OK CGSize sizeText = [labelText boundingRectWithSize:CGSizeMake(self.view.frame.size.width - 140, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil].size; return sizeText.height;}
IOS 控制項 - UITableView 中的cell 自適應高度