Dynamic Uicollectionview Inside Dynamic Uitableviewcell

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)

Create dynamic collectionView inside tableview cell

If I understand your problem correctly, you have more than one rows in an UITableView which have horizontal UICollectionViews. Those collection views have cells which have dynamic size based on the images inside them.

So the width of the UITableView is fixed, but the height for the row depends on the height of the UICollectionView, correct?

I would recommend using self-sizing cells in the UITableView. See the reference here:
https://developer.apple.com/library/archive/documentation/UserExperience/Conceptual/AutolayoutPG/WorkingwithSelf-SizingTableViewCells.html

After that, you need to find a way to calculate the height of the UICollectionView correctly, so the UITableView cell can determine the correct height. There are several ways to do it, for example by overriding the intrinsicContentSize property of the UICollectionView and returning the largest height of the images.

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



Related Topics



Leave a reply



Submit