美文网首页
UITableView动态计算Cell高度

UITableView动态计算Cell高度

作者: Miro丶K | 来源:发表于2017-03-17 09:35 被阅读0次

    #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;

    }

    相关文章

      网友评论

          本文标题:UITableView动态计算Cell高度

          本文链接:https://www.haomeiwen.com/subject/ozasnttx.html