iOS 动态布局计算可视区域tableView的高度

发布时间 2023-07-17 16:25:44作者: qqcc1388

一般我们计算tableView的高度通过contentSize属性去拿,但是如果我们cell的高度是动态的,拿到的高度就不准确,如何能拿到可视区域tableView的高度,可以通过以下方式:

    /// 计算tableView的高度
    [self.tableView reloadData];
    NSLayoutConstraint *heightOfTableViewConstraint = [NSLayoutConstraint constraintWithItem:self.tableView attribute:(NSLayoutAttributeHeight) relatedBy:(NSLayoutRelationEqual) toItem:self.containerView attribute:(NSLayoutAttributeHeight) multiplier:0.0 constant:1000];
    [self.containerView addConstraint:heightOfTableViewConstraint];
    
    [UIView animateWithDuration:0.0 animations:^{
        [self.tableView layoutIfNeeded];
        } completion:^(BOOL finished) {
            CGFloat heightOfTableView  = 0.0;
            // Get visible cells and sum up their heights
            NSArray * cells = self.tableView.visibleCells;
            for(UITableViewCell * cell in cells) {
                heightOfTableView += cell.frame.size.height;
            }
            heightOfTableViewConstraint.constant = heightOfTableView;
            self.totalHeight = self.totalHeight + heightOfTableView;
        }];