Auto Height of UICollectionView inside UITableView

2019-07-15 01:30发布

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 Custom Cell

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条回答
▲ chillily
2楼-- · 2019-07-15 01:49

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
}
查看更多
登录 后发表回答