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

一般我们计算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;
        }];

posted @   qqcc1388  阅读(233)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2019-07-17 Windows10安装秘钥大全
点击右上角即可分享
微信分享提示