iOS筆記之UITableView自動計算cell高度

方法一:使用系統(tǒng)自動計算cell高度

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = 
      [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return [cell.contentView systemLayoutSizeFittingSize:
      UILayoutFittingCompressedSize].height;
}

方法二:使用第三方庫
下載地址:UITableView-FDTemplateLayoutCell

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *cellReuseId = [self getReuseIdWithIndexPath:indexPath];  //獲取cell id
    CGFloat height = [tableView fd_heightForCellWithIdentifier:cellReuseId cacheByIndexPath:indexPath configuration:^(id cell) {
        [self configureCell:cell indexPath:indexPath];  //對cell進行賦值
    }];
    return height;
}

tips:使用fd的時候需要注意,cell在豎直方向的約束必須要撐滿
舉例說明:cell里面有一個label,進行約束設(shè)置.

錯誤示范:

[label mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.right.equalTo(self.contentView);
    make.centerY.equalTo(self.contentView);  //豎直方向約束是不滿的,雖然label會有一個本身的高度
}

正確做法:
法一:

[label mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.right.equalTo(self.contentView);
    make.centerY.equalTo(self.contentView); 
    make.top.bottom.equalTo(self.contentView);  //約束撐滿豎直方向
}

法二:

[label mas_makeConstraints:^(MASConstraintMaker *make) {
    make.edges.equalTo(self.contentView);
}];
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容