Auto height of UICollectionView inside UITableViewCell

I want to create a cell consisting of heading text, description text and a collection view. So I tried to create such a cell Custom cell

I added a top, end, and leading to a supervisor restriction for the title and description. Then I also add the top, bottom, end and leading constraint to my UICollectionView .

To automatically height my table cell, I override viewWillAppear

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

And in my custom class, I called layoutIfNeeded()

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

I want the whole cell in collectionView be shown, and my tableViewCell height will be adapted to it.

Is there any way to do this? Any help would be greatly appreciated. Thank!

+1
ios uitableview uicollectionview
Mar 28 '17 at 5:57
source share
1 answer

The custom size of the observer content for the collection view can change the height of the collection view according to its contents at run time.

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

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

Using the callback method below, you can set the runtime for viewing collections.

 override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { self.collectionViewHeight.constant = self.collectionView.contentSize.height } 
+1
Mar 28 '17 at 6:14
source share



All Articles