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

iOS 8 UITableView 自適應 cell 高度實作

編輯:iOS 開發綜合

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 中自行調整子視圖位置,否則多行文字會與其他元素重疊。

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