Chapter 9. Collection Views
A collection view (UICollectionView) is a UIScrollView that generalizes the notion of a table view (Chapter 8). Where a table view has rows, a collection view has items. (UICollectionView extends IndexPath so that you can refer to its item property instead of its row property, though in fact they are interchangeable.)
If you mentally substitute for items for rows, you’ll find that, knowing about table views, you know a great deal about collection views already:
-
The items are portrayed by reusable cells. These are UICollectionViewCell instances. If the collection view is instantiated from a storyboard, you can get reusable cells from the storyboard; otherwise, you’ll register a class or nib with the collection view.
-
A collection view can clump its items into sections.
-
A collection view has a data source (UICollectionViewDataSource) and a delegate (UICollectionViewDelegate), and it’s going to ask the data source Three Big Questions:
-
numberOfSections(in:) -
collectionView(_:numberOfItemsInSection:) -
collectionView(_:cellForItemAt:)
Alternatively, starting in iOS 13, you can use a UICollectionViewDiffableDataSource.
-
-
To answer the third Big Question, your data source will obtain a reusable cell by dequeuing it from the collection view:
-
dequeueReusableCell(withReuseIdentifier:for:)
-
-
A collection view allows the user to select a cell, or multiple cells. The delegate is notified of highlighting and selection.
-
Your code can rearrange the ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access