您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 動態計算 UITableViewCell 的高度

編輯:iOS 開發綜合

當 Cell 裡的文字長度不固定時,高度就不能寫死。核心思路是:先用 boundingRectWithSize: 算出文字實際佔的大小,再依此設定 Cell 高度。

在 cellForRowAtIndexPath 中計算內容尺寸

- (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 代表不限高。

在 heightForRowAtIndexPath 中回報高度

- (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 都被計算兩次,列表滾動時效能低落。
  • 使用快取:把算出來的高度用「indexPath 或內容雜湊值」當 key 存進字典快取,同一筆資料只算一次。
  • iOS 8 之後的自動化方案:如果 Cell 使用 Auto Layout,只要設定 tableView.rowHeight = UITableViewAutomaticDimension 並給予 estimatedRowHeight,系統就會依約束自動算出高度,完全不需要手動計算。
  • 呼叫方式有副作用:直接呼叫 delegate 方法取 cell 屬於破壞封裝的寫法,容易在不同 iOS 版本上出現非預期行為。

只有在 Cell 採用 frame 手動布局、或需要極致效能控制的舊專案中,才建議沿用這種手動計算方式。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved