提问人:Gunjan Rathore 提问时间:8/6/2020 最后编辑:Gunjan Rathore 更新时间:8/6/2020 访问量:2656
ScrollView里面的TableView,运行时如何计算tableview高度?
TableView inside ScrollView , How to calculate tableview height at runtime?
问:
滚动视图中有表格视图,对于完美的滚动需要表格视图的高度。但是有单元格的动态高度和单元格中的多个内容,其中包含动态数据,如图像(使用翠鸟库计算图像高度)和内容(行数为 0)。因此无法计算每个单元格的高度。所以我用它来获取细胞的高度:-
let totalCount = self.itemArray.data1.count + self.itemArray.data2.count
if totalCount != self.totalHeightOfTable.count {
//Appending height of cell
self.tableView.reloadData()
self.totalHeightOfTable.append(cell.frame.height)
self.heightOfPost = self.totalHeightOfTable
if totalCount == self.totalHeightOfTable.count {
// Call back to get height of tableView
self.getTotalHeightOfTableView?(self.totalHeightOfTable)
}
}
因为 tableView 在 scrollView 中,我无法动态或在运行时计算 tableView 每个单元格的高度。我在运行时得到的高度更大,并且在 tableView 的末尾有一个空白区域。因此,表视图的总高度始终大于表视图中所有单元格的总和。
答:
您可以通过以下方式使用 contentSize 的高度taleView.contentSize.height
欢迎来到 Stackoverflow!
您绝对可以获取 tableView 的高度,并从中获取高度。我一直在使用这种方法,每次都有效。contentSize
一种方法是添加一个观察者,如下所示:
tableView.addObserver(self, forKeyPath: "contentSize", options: .new, context: nil)
然后覆盖控制器的方法,如下所示:observeValue
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if let obj = object as? UITableView {
if obj == self.tableView && keyPath == "contentSize" {
if let newSize = change?[NSKeyValueChangeKey.newKey] as? CGSize {
let height = newSize.height // <----- your height!
}
}
}
}
补充一点,也许最好在你的 or 方法中删除该观察者。viewWillDisappear
deinit
我理解您的问题,即您想在tableview中使用灵活的单元格高度计算动态表高度,并根据此高度更新父滚动视图contentSize高度。
我想告诉你,请删除你所有的高度计算,只需将这个简单的函数放在你的视图控制器旁边。
重要:-如果从情节提要或以编程方式使用自动布局,请不要为表视图提供任何高度约束。
请妥善处理 tableview 和 scrollview 的变量名称,并分别替换它们。
//MARK:- viewDidLayoutSubviews will call after dynamic height calculation automatically
override func viewDidLayoutSubviews() {
//isScrollEnabled of table view should be dissable because our table is inside scrollview.
tableView.isScrollEnabled = false
//if above tableView.contentSize.height not zero and giving acurate value then proceed further and update our parent scroll view contentsize height for height.
print(tableView.contentSize.height)
//place some bottom peeding as you want
let bottomPedding:CGFloat = 30
//Finally update your scrollview content size with newly created table height + bottom pedding.
scrollview.contentSize = CGSize.init(width: scrollview.contentSize.width, height:tableView.contentSize.height + bottomPedding)
}
如果这行得通,那就太好了,休息一下,我们可以随时与我联系,我们会弄清楚的。[电子邮件保护]
评论