by Payal Gupta

How to make height of collection views dynamic in your iOS apps

Be dynamic, just like life…

1*58RjgkbswK_v3ofUG4z_qA

Table views and collection views have always been an integral part of iOS app development. We all might have came across various issues related to them. In this article, we’ll discuss one such problem statement related to collection views.

Problem Statement

Let’s assume we’ve a UICollectionView in a UITableViewCell and around 20 UICollectionViewCells that we need to render in it vertically. We can definitely implement that in the blink of an eye with the given data source.

Now comes the actual problem statement — we need the UITableViewCell to adjust its height dynamically according to its content. Also, the UICollectionView must be such that all the cells are displayed in one go, i.e. no scrolling allowed.

Long story short: make everything dynamic…

1*QxfoBsPpGFM707gho3k0eA
Fixed and Dynamic Height Collection View

Let’s start coding

A view in iOS calculates its height from its content, given there is no height constraint provided. Same goes for UITableViewCell.

For now, we’ll keep a single collectionView inside our tableViewCell with its leading, top, trailing and bottom constraints set to 0.

1*KOtsApDTjYA4J2oo-1mRYA
View Hierarchy

Since we haven’t provided any height constraint to the collectionView and neither do we know the its contentSize beforehand, then how will the tableViewCell calculate its height?

Solution

Dynamically calculating the collectionView’s height as per its contentSize is simply a 3 step process.

1. Subclass UICollectionView and override its layoutSubviews() and intrinsicContentSize , i.e.

The above code will invalidate the intrinsicContentSize and will use the actual contentSize of collectionView. The above code takes into consideration the custom layout as well.

2. Now, set DynamicHeightCollectionView as the collectionView’s class in storyboard.

1*w3eFLkfu3BvAg04hj__pPQ

3. One last thing, for the changes to take effect: you need to call layoutIfNeeded() on collectionView, after reloading collectionView’s data, i.e.

func configure(with arr: [String]) {   self.arr = arr   self.collectionView.reloadData()   self.collectionView.layoutIfNeeded() //Here..!!!}

And there you have it!

Sample Project

You can download the sample project from here.

Further reading

Don’t forget to read my other articles:

  1. Everything about Codable in Swift 4
  2. Everything you’ve always wanted to know about notifications in iOS
  3. Deep copy vs. shallow copy — and how you can use them in Swift
  4. Coding for iOS 11: How to drag & drop into collections & tables
  5. All you need to know about Today Extensions (Widget) in iOS 10
  6. UICollectionViewCell selection made easy..!!

Feel free to leave comments in case you have any questions.