[英]How to expand/shrink UICollectionViewCell height when a UITableview with dynamic cell height is placed inside?
[英]Dynamic height of UITableView inside UIcollectionViewCell
我有一个UICollectionViewCell,里面有一个UTableView。 我想根据其中的内容动态计算UITableView的高度。 这意味着,UITableView不应滚动,而应根据其内容增加/减小其高度。
您可以使用如下所示的自调整表视图:
class SelfSizingTableView: UITableView {
override var intrinsicContentSize: CGSize {
return CGSize(width: UIView.noIntrinsicMetric, height: contentSize.height)
}
override var contentSize: CGSize {
didSet {
invalidateIntrinsicContentSize()
}
}
}
另外,您必须确保在集合视图单元格中正确设置约束(从集合视图单元格的顶部到底部的全套约束)。
我去过那儿。 有多种方法可以做到这一点,特别是如果您的行确实具有恒定的高度,那应该很容易。 将行数乘以恒定的高度,瞧,您就有了tableView的高度。
但是,如果在collectionViewCell或tableViewCell(它们相同)中具有tableView的动态单元格高度,则需要另一种方法。
我的方法是观察keyPath contentSize
。 这是完美的,我在我的主要生产项目中一直在使用它。 这是我使用的完整代码块,包括注释/文档;)
/**
Important Notes, as of 12/18/2018, 9:41PM, a eureka moment:
- No need for label height.
- Needs a reference for tableViewHeight.
- After observing the newSize data, update the constraint's offset of the tableViewHeight reference.
- And then let know the controller to not reload the data of the tableView but rather begin and end updates only.
- beginUpdate() and endUpdate() lets the tableView to update the layout without calling the cellForRow, meaning without calling the setupCell method.
*/
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if let obj = object as? LLFTableView, obj.tag == 444 {
if obj == self.tableView && keyPath == "contentSize" {
if let newSize = change?[NSKeyValueChangeKey.newKey] as? CGSize {
// Edit heightOfTableViewConstraint's constant to update height of table view
llfPrint("New Size of the tableView: \(newSize) ✅✅✅✅✅")
DispatchQueue.main.async {
self.constraint_TableViewHeight?.update(offset: newSize.height)
self.delegate?.reloadData()
}
}
}
}
}
那么,在实现此类reloadData
委托方法的控制器或viewModel中会发生什么? 它调用了另一个委托方法,只是让控制器(其中包含超级tableView)知道我们正在更新单元格的高度。
self.tableView.beginUpdates()
self.tableView.endUpdates()
而已! :) 我希望这有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.