設(shè)置cell動(dòng)態(tài)高度有好幾種方法:
1.使用SDAutoLayout:http://blog.csdn.net/gsd_ios/article/details/50219713
2.使用Masonry:http://www.reibang.com/p/3fc1b14e3f97
3.使用UITableView+FDTemplateLayoutCell.h 參考地址同上。
4.添加一個(gè)SampleCell用來(lái)計(jì)算高度:http://blog.csdn.net/horisea/article/details/52025886
我選了最后一種方法冶忱,原因是我的cell不是完全AutoLayout。最后一種方法自定義程度比較高遏乔。理解一下第四種方法,其實(shí)就是要先用一種方法根據(jù)數(shù)據(jù)Model計(jì)算出cell高度发笔,然后渲染出cell視圖盟萨。并將高度存儲(chǔ)在數(shù)組中,方便使用了讨,省略重復(fù)計(jì)算捻激。
controller中:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
CGFloat height = [[self.heightArray h_safeObjectAtIndex:indexPath.row] floatValue];
if (height) {
return height;
}else{
height = [[FoundCellHeight shareInstance] cellHeightWithModel:self.datalist[indexPath.row]];
[self.heightArray addObject:@(height)];
return height;
}
}
計(jì)算高度的類中:
+ (FoundCellHeight *)shareInstance {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_sharedInstance = [[FoundCellHeight alloc] init];
});
return _sharedInstance;
}
- (CGFloat)cellHeightWithModel:(FoundModel *)model {
CGFloat labelHeight = [model.desc sizeWithLabelWidth:kScreenWidth - 24 font:[UIFont systemFontOfSize:15]].height;
CGFloat picHeight;
if (model.picArr.count == 0) {
picHeight = 0;
}else if (model.picArr.count <= 3) {
picHeight = 98;
}else {
picHeight = 98*2;
}
return labelHeight + picHeight + 227-88-18;
}