iOS 8 帶來了 UITableView 的 Self Sizing Cells 特性,從此不必再為每個 cell 手動計算高度。在 iOS 8 之前,如果要在 cell 中展示長度不定的內容,必須自己量測文字尺寸再賦值給 rowHeight 或實作 heightForRowAtIndexPath:;現在系統可以代勞。
只要兩行設定即可啟用:
_tableView.rowHeight = UITableViewAutomaticDimension; // 預估高度可隨意設定,例如 44 或其他數值, // 它只用於初期滾動條估算,不影響最終高度 _tableView.estimatedRowHeight = 44;
@interface ViewController () <UITableViewDataSource, UITableViewDelegate>
// 資料源
@property (nonatomic, strong) NSMutableArray *dataArray;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 讓系統自動計算行高
_tableView.rowHeight = UITableViewAutomaticDimension;
_tableView.estimatedRowHeight = 44;
_dataArray = [NSMutableArray arrayWithCapacity:0];
[_dataArray addObjectsFromArray:@[@"第一則內容", @"第二則內容", @"第三則內容"]];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return _dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *identifier = @"ID";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:identifier];
}
cell.textLabel.text = _dataArray[indexPath.row];
cell.textLabel.numberOfLines = 0; // 必須為 0,才能多行換行
return cell;
}
@end
執行結果:高度由系統自動算好,內容多長撐多高。
第一,cell 內的內容必須允許換行。以 textLabel 為例,要設 numberOfLines = 0;若使用自訂的 UILabel,同樣要關閉行數限制。
第二,若使用 Auto Layout 佈局 cell 內容,垂直方向上的約束必須完整且能推導出高度,否則系統會算出錯誤值。若沿用 frame 手動佈局,則需要在 layoutSubviews 中自行調整子視圖位置,否則多行文字會與其他元素重疊。