我正在寻找一种实现布局的方法,如下所示:
基本上,它由UICollectionViewCell
组成,其中包含UITableView
的实例。 UICollectionViewCell
包含少量其他补充元素,但与该问题无关。
我希望UITableView被完全展开,即显示所有单元格。我选择了UITableView
,因为它恰好具有我需要的样式。
问题是UITableView
没有完全展开。从技术上讲,我希望UITableView
的大小等于contentSize
。
我正在使用自动布局来计算UICollectionViewCell
大小,因此“可调整大小的” UITableView会派上用场。
到目前为止,我已经尝试使用这种方法:
import UIKit
final class FullSizeTableView: UITableView {
override var intrinsicContentSize: CGSize {
return contentSize
}
}
然后使用FullSizeTableView
中的UICollectionViewCell
:
我已将UITableView
从四个侧面全部约束,从顶部到UIStackView
以及从底部,左,右到ContentView
。
但是,结果看起来像这样:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4 /// Meanwhile, Returning 4 rows in the DataSource
}
因此,我想AutoLayout似乎并不尊重UITableView
的实际大小。我没有考虑的潜在陷阱是什么?
我对UITableView
的目标是始终完全展开并以完整尺寸显示。
Update1:
您可以计算每行的高度,并将tableView的高度设置为该高度的总和。
这是一个应该执行此操作的简单函数(尚未测试过,因此可能需要一些调整):
func calculateTableViewContentHeight(tableView: UITableView) -> CGFloat {
let rows = tableView.numberOfRows(inSection: 0) // adapte to your needs
var totalHeight: CGFloat = 0
for i in 0..<rows {
totalHeight += tableView.rectForRow(at: IndexPath(row: i, section: 0)).height
}
return totalHeight
}