Uicollectionview Inside a Uitableviewcell - Dynamic Height

Non-Scrolling UICollectionView inside UITableViewCell Dynamic Height

You need to bind your collectionView delegate/datasource with TableViewCell and need to use below func in tableViewcell. Make sure to turn off the CollectionView Scrolling.

override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {

self.layoutIfNeeded()
let contentSize = self.cvSubcategory.collectionViewLayout.collectionViewContentSize
if self.cvSubcategory.numberOfItems(inSection: 0) < 4 {
return CGSize(width: contentSize.width, height: 120) // Static height if colview is not fitted properly.
}

return CGSize(width: contentSize.width, height: contentSize.height + 20) // 20 is the margin of the collectinview with top and bottom
}

Your project sample solution : https://github.com/thedahiyaboy/DynamicCollectionApp


For future purpose you can take ref from this post : Dynamic CollectionViewCell In TableViewCell Swift

Dynamic UICollectionView inside dynamic UITableViewCell

Create a subclass for collectionView and override intrinsicContentSize.

class DynamicCollectionView: UICollectionView {
override func layoutSubviews() {
super.layoutSubviews()
if !__CGSizeEqualToSize(bounds.size, self.intrinsicContentSize) {
self.invalidateIntrinsicContentSize()
}
}

override var intrinsicContentSize: CGSize {
return collectionViewLayout.collectionViewContentSize
}
}

  1. In Interface builder change the class of your collectionView to DynamicCollectionView (subclass UICollectionView).

  2. Set estimated cell size of UICollectionViewFlowLayout.

        flowLayout.estimatedItemSize = CGSize(width: 1,height: 1)


Related Topics



Leave a reply



Submit