Category Archives: Objective-C

Variable Height of a UICollectionViewCell Depending on Data

(Code on BitBucket – Built with XCode 6.4)

Back to the basics: UICollectionViews + Objective-C!

Let’s have a look at the simple yet common task of changing the height of a UICollectionViewCell depending on its content (in this case a piece of text).

Screen Shot 2015-08-19 at 11.43.52


The Interface

In Interface Builder we will create a UICollectionView with the main controller being it’s delegate and data source. Add a UILabel and a UIButton to the prototype cell and set its class to QuoteCell. Most importantly we need to set the UILayoutConstraints for the cell’s subviews. This is because what we’ll be doing is “stretching” the cell in height and everything inside of is needs to adjust accordingly. The button must be pinned at the bottom and the label on the sides.

Screen Shot 2015-08-19 at 11.53.19


The QuoteCell class has the IBOutlets defined and ready to be connected via IB.

Back in our view controller we have a data NSArray that will hold the quotes as strings. We also extend the delegate by setting it to UICollectionViewDelegateFlowLayout. This is the delegate that will call the function that will set the cell’s height

On viewDidLoad we create the strings.

We will implement the most basic methods of the UICollectionViewDataSource so as to display the cells with the quotes passed in their labels.

Adjusting the Height

The million dollar function for our project is:

Calculate the size of the text and add an arbitrary height as a padding (I have found it impossible to calculate exactly how much height a font needs to display correctly). We use CGFLOAT_MAX so that the cells can extend for as much as they need. Due to the constraints, the elements should adjust nicely inside of the cell.

For more tutorials on Collection Views

[catlist name=”UICollectionView”]