做列表時最麻煩的往往不是版面,而是「每一列的內容長度不一樣」。圖片要等比例縮放、文字要依字型換行計算高度,最後還要把兩者加上間距加總。以下示範如何拆解這個計算過程。
#define kFontSize 14 #define kPhotoCell_Width 300 #define kPhotoCell_MarginBetween 3 #define kPhotoCell_TitleLabel_Height 25
+ (CGFloat)heightForRowWithModel:(PhotoInfo *)photoInfo {
// 1. 圖片的高度(讓圖片等比例縮放)
UIImage *image = [UIImage imageWithContentsOfFile:
[[NSBundle mainBundle] pathForResource:@"TSummer" ofType:@"png"]];
CGFloat imageHeight = [self heightForImage:image];
// 2. 文字的高度
CGFloat textHeight = [self heightForText:photoInfo.introduction];
// 3. 回傳 cell 的總高度
return kPhotoCell_TitleLabel_Height + imageHeight + textHeight
+ 4 * kPhotoCell_MarginBetween;
}
核心邏輯是「寬度固定、高度按比例縮放」:先算出寬度的縮放比例,再用同一個比例去縮高度。
+ (CGFloat)heightForImage:(UIImage *)image {
// (1) 取得圖片原始尺寸
CGSize size = image.size;
// (2) 求出縮放比例
CGFloat scale = kPhotoCell_Width / size.width;
CGFloat imageHeight = size.height * scale;
return imageHeight;
}
這裡的關鍵是 屬性字典必須與顯示時使用的字型一致。如果計算時用 14pt、畫面上卻用 16pt 顯示,算出來的高度就會偏小,導致文字被裁切。
+ (CGFloat)heightForText:(NSString *)text {
// 設定計算時的字型,作為高度估算基準
NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:kFontSize]};
return [text boundingRectWithSize:CGSizeMake(kPhotoCell_Width, 1000)
options:(NSStringDrawingUsesFontLeading |
NSStringDrawingUsesLineFragmentOrigin)
attributes:attributes
context:nil].size.height;
}
記得做快取:boundingRectWithSize: 並不便宜,若放在 tableView:heightForRowAtIndexPath: 中每次滾動都重算,列表會明顯卡頓。實務做法是先把高度算好存進 model 或另外一個字典,以 indexPath 為 key 取用。
圖片不要從 bundle 讀:範例用 imageWithContentsOfFile: 從本地讀取是為了示範,真實場景中圖片多半來自網路,此時應先讀取圖片本身的尺寸(例如用 SDWebImage 的 sd_imageWithData: 只解出尺寸而不解碼整張圖),避免為了算高度而載入大圖。
間距不要寫死成 4 倍:範例中的 4 * kPhotoCell_MarginBetween 隱含了「圖片上下各一個間距、文字上下各一個間距」的假設。版面一調整就容易算錯,建議改成顯式加總各段間距,可讀性更好。
iOS 7 以上的替代方案:若專案已不支援舊系統,可以直接用 Auto Layout 搭配 UITableViewAutomaticDimension 與 estimatedRowHeight,讓系統自行計算,省下所有手動測量的程式碼。