gpt4 book ai didi

ios - UITableViewCell 中 UICollectionView 的自动高度

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:33:38 25 4
gpt4 key购买 nike

我想创建一个包含标题文本、描述文本和 Collection View 的单元格。所以我试着创建一个像这样的单元格 Custom Cell

我为 titledescription 添加了 top、trailing 和 leading to superview 约束。然后,我还将顶部、底部、尾部和前导约束添加到我的 UICollectionView

对于我的 tableview 单元格的自动高度,我覆盖了 viewWillAppear

override func viewWillAppear(_ animated: Bool) {
tableView.estimatedRowHeight = 300
tableView.rowHeight = UITableViewAutomaticDimension
}

在我的自定义单元类中,我调用了 layoutIfNeeded()

public func setRowWithData(model: DataModel) {
// set your view here
contentView.layoutIfNeeded()
}

我想要的是,显示 collectionView 中的所有单元格,并且我的 tableViewCell 的高度将适应它。

有什么办法吗?任何帮助,将不胜感激。谢谢!

最佳答案

您可以使用 Collection View 的内容大小观察器在运行时根据其内容更改 Collection View 的高度。

要将观察者添加到您的 Collection View 中,您可以使用以下方法。

self.collectionView.addObserver(self, forKeyPath: "contentSize", options:   NSKeyValueObservingOptions.old.union(NSKeyValueObservingOptions.new), context: nil)

通过使用下面的回调方法,您可以设置 Collection View 高度运行时。

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
self.collectionViewHeight.constant = self.collectionView.contentSize.height
}

关于ios - UITableViewCell 中 UICollectionView 的自动高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43061624/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com