(I tested this with iOS 9, 10, and 11)
In newer versions of iOS (maybe 9?), you can do away with custom height calculation of collection view cells, and rely entirely on flow layout’s estimatedItemSize
function and autolayout to automatically find the correct height and width. However, sometimes a custom, manual, height calculation is required. Examples would be when you want to fit the width of a cell the entire width of the screen, or when you want to force a height to be 0, then you’ll need manual calculation.
As a reference for myself and others, I documented this down so no one will need to fiddle with this again in the future. So assuming you have a collection view in place, and a custom cell subclass, let’s put in the pieces to make the above image work.
Reference Code
Within the ViewController class:
// 1.
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout
- Whichever class you have that’s going to be doing the height calculation needs to conform to
UICollectionViewDelegateFlowLayout
// 2.
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! TestCell
configure(cell: cell)
return cell
}
// 3.
func configure(cell: TestCell) {
cell.titleLabel.text = "Ooh woo, I'm a rebel just for kicks, now. I been feeling it since 1966, now. Might've had your fill, but you feel it still"
cell.subtitleLabel.text = "Feel It Still, by Portugal. The Man. Pretty good song I'm listening to while writing the configure method of this cell. "
}
// 4.
let sizingCell = TestCell()
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
// 5.
… Read the rest