Auto Height of UICollectionView inside UITableViewCell

╄→尐↘猪︶ㄣ 提交于 2019-12-24 02:48:10

问题


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

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.

For auto height my tableview cell, I override viewWillAppear

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

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

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

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!


回答1:


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
}


来源:https://stackoverflow.com/questions/43061624/auto-height-of-uicollectionview-inside-uitableviewcell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!