7.5 · Compositional layout, diffable data sources, cell reuse and prefetching
Collection views are the workhorse of modern UIKit, and, with list layouts, now replace most table views. Four ideas cover them: a declarative layout, an identity-based data source, reusable cells and cheap scrolling.
Mental model. Describe the layout as item, group and section. Describe the data as a snapshot of identifiers. Let UIKit work out the difference and reuse cells to show it.
Layout and data
Compositional layout and the diffable data source.
- How does compositional layout describe a collection view, and how do you read its output?
UICollectionViewCompositionalLayout builds a layout from three nested pieces. An item (NSCollectionLayoutItem) describes one cell’s size. A group arranges… - How does a diffable data source work, and what does it require of your item identifiers?
A UICollectionViewDiffableDataSource<Section, Item> replaces the old “answer numberOfItems and hope” protocol. You build an immutable snapshot…
Cells and performance
Reuse bugs, prefetching and self-sizing.
- How does cell reuse work, and what are the classic reuse bugs?
Collection and table views do not create a cell per item. They keep a small pool and reuse cells as they scroll off screen: you ask the view to… - How do prefetching and self-sizing cells keep scrolling smooth, and what can still make it janky?
Prefetching is on by default (isPrefetchingEnabled is true): the collection view asks for cells slightly before they are needed, spreading creation cost across…
More in UIKit
- 7.1 · Hit testing, the responder chain and gesture recognisers
- 7.2 · UIView and CALayer, frame, bounds and center
- 7.3 · View controller lifecycle, containment, presentation and transitions
- 7.4 · Navigation, tab, split and page controllers
- 7.6 · UITableView, still asked and still everywhere
- 7.7 · Trait collections, size classes, safe area, keyboard and appearance
- 7.8 · Keyboard shortcuts, pointer, Apple Pencil and multitasking
- 7.9 · Hosting SwiftUI in UIKit and UIKit in SwiftUI
- 7.10 · Initialisers, stack views, scroll views and modern buttons
- 7.11 · Layout passes, retain cycles and menus
- 7.12 · Refreshing diffable cells, outlines and carousel layouts
- 7.13 · View-tree exercises and long navigation stacks