Implementing collectionViewContentSize

The collectionViewContentSize property is used by the collection view to determine the size of its contents. It's important for the collection view to know the size because this size is used for the scroll indicators that hint to the user how far along they are when scrolling in a list. Another reason this property is important is because it will give the collection view enough information to determine in which direction it should scroll.

The implementation for this property uses the number of rows in the collection view and the number of columns in the collection view. These numbers will be multiplied by the sizing of each item while the spacing between the items is taken into account.

Finally, a CGSize is returned that represents the size of the collection view's entire contents. The following snippet shows the implementation:

override var collectionViewContentSize: CGSize { 
let width = CGFloat(numColumns) * itemSize.width + CGFloat(numColumns - 1) * itemSpacing
let height = CGFloat(numRows) * itemSize.height + CGFloat(numRows - 1) * itemSpacing

return CGSize(width: width, height: height)
}

Because the layout is properly prepared, determining the size for the entire layout isn't very complex. Two simple calculations are enough to figure out the size of the collection view's contents.