[英]Calculate UITableView expected height
I have UITableView
with 2 cells that do AutoLayout (quite simple, UILabel
and UISwitch
, and UILabel
and UIImageView
).我有
UITableView
与 2 个单元格执行 AutoLayout (非常简单, UILabel
和UISwitch
,以及UILabel
和UIImageView
)。 I want to get tableView heihgt
.我想得到 tableView
heihgt
。 UITableView
reside to UIView
, so i did following: UITableView
驻留在UIView
,所以我做了以下:
override func layoutSubviews() {
super.layoutSubviews()
if !isLayoutSubviewsDone {
expectedHeight = tableView.contentSize.height
isLayoutSubviewsDone = true
didLayoutSubivews?()
}
}
unfortunately, tableView.contentSize.height
is smaller that it should be.不幸的是,
tableView.contentSize.height
比它应该的要小。 for about 20%.约 20%。 How to get exact height amount?
如何获得准确的高度量?
How to get exact height amount?
如何获得准确的高度量?
There is no magic way to size a table to its contents.没有什么神奇的方法可以根据内容调整表格的大小。 The table view has no automatic size.
表视图没有自动大小。 It is not magically sized by the heights of its cells.
它的大小并不是由细胞的高度神奇地决定的。 You have to work out the height of every cell yourself, one at a time, and add them up.
您必须自己计算每个单元格的高度,一次一个,然后将它们相加。
If you add observer to TableView, I'm sure you will get exact table view height.如果您将观察者添加到 TableView,我相信您将获得准确的表格视图高度。 Try below code.
试试下面的代码。
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
expectedHeight.constant = tableView.contentSize.height
}
//MARK:- Add Observer on Reload tableView //MARK:- 在重新加载 tableView 上添加观察者
tableView.addObserver(self, forKeyPath: "tableViewObserver", options: [], context: nil)
tableView.reloadData()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.