UITableView动态计算Cell高度

#pragma mark - 动态计算cell高度

+ (CGFloat)kCalculation_HeightForCellWithTableView:(UITableView *)tableView byIdentifier:(NSString *)identifier configuration:(void (^)(id cell))configuration {

NSAssert(identifier.length > 0, @"Expect a valid identifier - %@", identifier);    NSMutableDictionary*templateCellsByIdentifiers = objc_getAssociatedObject(tableView, _cmd);

if (!templateCellsByIdentifiers) {

templateCellsByIdentifiers = @{}.mutableCopy;

objc_setAssociatedObject(tableView, _cmd, templateCellsByIdentifiers, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

}

UITableViewCell *cell = templateCellsByIdentifiers[identifier];

if (!cell) {

cell = [tableView dequeueReusableCellWithIdentifier:identifier];

NSAssert(cell != nil, @"Cell must be registered to table view for identifier - %@", identifier);

cell.contentView.translatesAutoresizingMaskIntoConstraints = NO;

templateCellsByIdentifiers[identifier] = cell;

}

[cell prepareForReuse];

if (configuration) {

configuration(cell);

}

CGFloat contentViewWidth = CGRectGetWidth(tableView.frame);

if (cell.accessoryView) {

contentViewWidth -= 16 + CGRectGetWidth(cell.accessoryView.frame);

} else {

static const CGFloat systemAccessoryWidths[] = {

[UITableViewCellAccessoryNone] = 0,

[UITableViewCellAccessoryDisclosureIndicator] = 34,

[UITableViewCellAccessoryDetailDisclosureButton] = 68,

[UITableViewCellAccessoryCheckmark] = 40,

[UITableViewCellAccessoryDetailButton] = 48

};

contentViewWidth -= systemAccessoryWidths[cell.accessoryType];

}

CGFloat fittingHeight = 0;

if (contentViewWidth > 0) {

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

[cell.contentView addConstraint:widthFenceConstraint];

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

[cell.contentView removeConstraint:widthFenceConstraint];

}

if (fittingHeight == 0) {

fittingHeight = 44;

}

return fittingHeight;

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容