IOS8之后 如果使用自动布局,就不用再需要手动计算UITableViewCell高度
注意事项:
1.Cell高度设置自动适配,预设高度
_tableView.rowHeight = UITableViewAutomaticDimension;
_tableView.estimatedRowHeight = 134.f;
2.在重用Cell的方法中实现,不要在layoutSubviews方法里面设置布局。
-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
//在这里实现布局
[self mas_makeConstraints];
}
3.还有一种方式可以缓存高度,提高减少高度计算.
- (CGSize)systemLayoutSizeFittingSize:(CGSize)targetSize NS_AVAILABLE_IOS(6_0); // Equivalent to sending -systemLayoutSizeFittingSize:withHorizontalFittingPriority:verticalFittingPriority: with UILayoutPriorityFittingSizeLevel for both priorities.
- (CGSize)systemLayoutSizeFittingSize:(CGSize)targetSize withHorizontalFittingPriority:(UILayoutPriority)horizontalFittingPriority verticalFittingPriority:(UILayoutPriority)verticalFittingPriority NS_AVAILABLE_IOS(8_0);
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
BSQuestionsModel * model = _dataArray[indexPath.section];
return model.cell_height?:UITableViewAutomaticDimension;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
BSQuestionsModel * model = _dataArray[indexPath.section];
BSQuestionsTableViewCell * cell = [BSQuestionsTableViewCell cellForTableView:tableView model:model];
//高度缓存
CGFloat height = [cell systemLayoutSizeFittingSize:CGSizeMake(tableView.frame.size.width, 0) withHorizontalFittingPriority:UILayoutPriorityRequired verticalFittingPriority:UILayoutPriorityFittingSizeLevel].height;
model.cell_height = height;
}