如何在单元格动态调整大小时获取UITableView的高度? [英] How to get height of UITableView when cells are dynamically sized?

查看:785
本文介绍了如何在单元格动态调整大小时获取UITableView的高度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个UITableView,其中包含动态调整大小的单元格。这意味着我已设置:

I have a UITableView with cells that are dynamically sized. That means I have set:

tableView.estimatedRowHeight = 50.0
tableView.rowHeight = UITableViewAutomaticDimension

现在我想获得整个表格视图的高度。我尝试通过 tableView.contentSize.height 来获取它,但这只返回估计的行高,而不是表视图的实际动态高度。

Now I want to get the height of the whole table view. I tried getting it through tableView.contentSize.height but that only returns the estimated row height, and not the actual dynamic height of the table view.

如何获得整个表格视图的动态高度?

How do I get the dynamic height of the whole table view?

推荐答案

我终于砍掉了一个解决方案:

I finally hacked out a solution:

tableView.contentSize.height 对于动态单元格不起作用,因为它们只会返回cells * estimatedRowHeight

tableView.contentSize.height will not work for dynamic cells because they will only return the number of cells * estimatedRowHeight.

因此,要获取动态表格视图高度,请查找所有可见单元格,以及总结他们的高度。请注意,这仅适用于比屏幕短的表视图。

Hence, to get the dynamic table view height, you look for all visible cells, and sum up their heights. Note that this only works for table views that are shorter than your screen.

然而,在我们执行上述操作以查找可见单元格之前,重要的是要知道注意我们需要在屏幕上获取表格视图,以便我们可以获得可见细胞。为此,我们可以将表格视图的高度约束设置为一些任意大的数字,以便它显示在屏幕上:

However, before we do the above to look for visible cells, it is important to know that note we need to get the table view on the screen so that we can obtain visible cells. To do so, we can set a height constraint for the table view to some arbitrarily large number just so it appears on the screen:


  1. 设置表视图约束的高度:

  1. Set height of table view constraint:

// Class variable heightOfTableViewConstraint set to 1000
heightOfTableViewConstraint = NSLayoutConstraint(item: self.tableView, attribute: .height, relatedBy: .equal, toItem: containerView, attribute: .height, multiplier: 0.0, constant: 1000)
containerView.addConstraint(heightOfTableViewConstraint)


  • 调用tableView.layoutIfNeeded(),完成后,查找可见单元格,总结高度,然后编辑 heightOfTableViewConstraint

    UIView.animate(withDuration: 0, animations: {
        self.tableView.layoutIfNeeded()
        }) { (complete) in
            var heightOfTableView: CGFloat = 0.0
            // Get visible cells and sum up their heights
            let cells = self.tableView.visibleCells
            for cell in cells {
                heightOfTableView += cell.frame.height
            }
            // Edit heightOfTableViewConstraint's constant to update height of table view
            self.heightOfTableViewConstraint.constant = heightOfTableView
    }
    


  • 这篇关于如何在单元格动态调整大小时获取UITableView的高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆