UITableViewCell 内 UICollectionView 的自动高度 [英] Auto Height of UICollectionView inside UITableViewCell

查看:61
本文介绍了UITableViewCell 内 UICollectionView 的自动高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个包含标题文本、描述文本和集合视图的单元格.所以我尝试创建一个这样的单元格

I want to create a cell that consist of title text, description text, and a collection view. So I tried to created a cell like this

我为titledescription 添加了顶部、尾部和导致超级视图约束.然后我还将顶部、底部、尾随和前导约束添加到我的 UICollectionView.

I added top, trailing, and leading to superview constraint for title and description. Then I also add top, bottom, trailing, and leading constraint to my UICollectionView.

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

For auto height my tableview cell, I override viewWillAppear

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

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

And in my custom cell class, I called layoutIfNeeded()

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

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

What I want is, all of cell in collectionView is showed and my tableViewCell's height will adapt into it.

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

Is there any way to do it? Any help would be appreciated. Thank you!

推荐答案

您可以使用集合视图的内容大小观察者在运行时根据其内容更改集合视图的高度.

You can user content size observer of collection view to change the height of collection view according to its content at runtime.

要将观察者添加到您的集合视图中,您可以使用以下方法.

To add the observer to your collection view you can use below method.

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

通过使用下面的回调方法,您可以设置集合视图高度运行时.

By using below callback method you can set the collection view height runtime.

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

这篇关于UITableViewCell 内 UICollectionView 的自动高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆