iOS 代碼計(jì)算cell高度自適應(yīng)

1.xib cell

1 先 property cell

@property (nonatomic, strong)? ZHCalculateTableViewCell *prototypeCell;

2.獲取cell

self.prototypeCell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];

3.計(jì)算cell高度

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{

ZHCalculateTableViewCell *cell = self.prototypeCell;// 必須將對(duì)象傳給一個(gè)新對(duì)象

cell.contentView.translatesAutoresizingMaskIntoConstraints = NO;

[self configureCell:cell atIndexPath:indexPath];//必須先對(duì)Cell中的數(shù)據(jù)進(jìn)行配置使動(dòng)態(tài)計(jì)算時(shí)能夠知道根據(jù)Cell內(nèi)容計(jì)算出合適的高度

/*------------------------------重點(diǎn)這里必須加上contentView的寬度約束不然計(jì)算出來的高度不準(zhǔn)確-------------------------------------*/

CGFloat contentViewWidth = CGRectGetWidth(self.tableView.bounds);

NSLayoutConstraint *widthFenceConstraint = [NSLayoutConstraint constraintWithItem:cell.contentView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:contentViewWidth];

[cell.contentView addConstraint:widthFenceConstraint];

// Auto layout engine does its math

CGFloat fittingHeight = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;

[cell.contentView removeConstraint:widthFenceConstraint];

return fittingHeight+2*1/[UIScreen mainScreen].scale;//必須加上上下分割線的高度

}

2.Masonry

1.第一種直接在cell里加一個(gè)加號(hào)方法

+(CGFloat)heightWithModel:(TestModel*)model{

TestCell*cell=[[TestCellalloc]initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:@""];

[cellconfigCellWithModel:model];

[celllayoutIfNeeded];

CGRectframe=cell.descLabel.frame;

returnframe.origin.y+frame.size.height+20;

}

2.用UITableView+FDTemplateLayoutCell計(jì)算
git地址? https://github.com/yolii/Masonry-FDTemplateLayoutCell

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

return [tableView fd_heightForCellWithIdentifier:kYLLayoutTableViewCell cacheByIndexPath:indexPath configuration:^(YLLayoutTableViewCell *cell) {

[cell setFeed:[self.viewModel.feedArray objectAtIndex:indexPath.row]];

}];

}

3.自適應(yīng),在cell里就把cell.contentView的大小約束對(duì)

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

return UITableViewAutomaticDimension;

}

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

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

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