當 Cell 裡的文字長度不固定時,高度就不能寫死。核心思路是:先用 boundingRectWithSize: 算出文字實際佔的大小,再依此設定 Cell 高度。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
self.mainTitle = [[UILabel alloc] init];
self.mainTitle.numberOfLines = 0; // 關鍵:允許換行
self.mainTitle.font = [UIFont fontWithName:@"Hiragino Sans GB" size:14];
self.mainTitle.text = cell_info.title;
self.mainTitle.textColor = [UIColor grayColor];
// 依可用寬度計算文字實際佔用的矩形
CGSize titleSize = [self.mainTitle.text boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width - 20, 0)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName : self.mainTitle.font}
context:nil].size;
self.rowHeight = titleSize.height;
self.mainTitle.frame = CGRectMake(15, 3, titleSize.width, titleSize.height);
[cell.contentView addSubview:self.mainTitle];
// 依子元件高度累加出 Cell 高度
CGRect cellFrame = [cell frame];
cellFrame.origin = CGPointMake(0, 0);
cellFrame.size.height = self.mainTitle.frame.size.height + 5 + self.imgOne.frame.size.height + 5;
[cell setFrame:cellFrame];
return cell;
}
兩個要點:numberOfLines = 0 讓 label 能撐開成多行;boundingRectWithSize: 的寬度必須傳入「實際可用寬度」(這裡是螢幕寬度扣掉左右邊距),高度傳 0 代表不限高。
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.section == 0)
{
return 160;
}
else
{
UITableViewCell *cell = [self tableView:self.tableView cellForRowAtIndexPath:indexPath];
return cell.frame.size.height;
}
}
上面這段程式碼能跑,但存在幾個明顯缺陷,實務上建議改用下面的做法:
heightForRowAtIndexPath: 裡直接呼叫 cellForRowAtIndexPath: 會額外建立一次 cell,等於每個 cell 都被計算兩次,列表滾動時效能低落。tableView.rowHeight = UITableViewAutomaticDimension 並給予 estimatedRowHeight,系統就會依約束自動算出高度,完全不需要手動計算。只有在 Cell 採用 frame 手動布局、或需要極致效能控制的舊專案中,才建議沿用這種手動計算方式。