Collection Views didn’t exactly make their way into SwiftUI during WWDC 2020, but that didn’t stop UICollectionView
from receiving some powerful new updates.
CompositionalLayouts
and DiffableDataSources
were introduced in iOS 13 CollectionViews
and brought more flexibility in constructing layouts and data sources for our UICollectionView
.
With iOS 14, there are three new additions to the CollectionView APIs for layouts, data sources, and cells — the three pillars of constructing collection views:
Lists
are a new addition to CompositionalLayouts
and bring a UITableView
-like appearance in CollectionViews
.UICollectionView.CellRegistration
lets you configure cells in a completely different way using new Configuration APIs. Also, there’s a new UICollectionViewListCell
concrete class that provides cells with list-like content styling by default.In the next few sections, we’ll discuss the first two additions. Let’s see how to construct layouts and cells in UICollectionView
in the new iOS 14 way.
iOS 14 introduces a brand new Cell Configuration API for configuring our CollectionView and TableView cells.
This means that we don’t need to set properties directly on the UITableViewCell
and UICollectionViewCell
like we did earlier.
The new configuration API lets us use a content configuration to set the cell’s content and styling or update it based on different states:
let cellRegistration = UICollectionView.CellRegistration<UICollectionViewCell, String> { cell, indexPath, name in
var content = UIListContentConfiguration.cell()
content.text = name
cell.contentConfiguration = content
}
For UICollectionViews
, we have a new UICollectionViewListCell
. We can directly fetch its default configuration in the following way:
var content = listCell.defaultContentConfiguration()
In doing so, we’re able to get rid of using cell identifiers and the obligatory if let
and guard let
statements we used to write to ensure that the cell was registered.
More importantly, we’re not directly accessing the cell’s label and image property anymore, which allows us to compose configurations that can be used across TableView
, CollectionView
, and custom cells.
Aside from contentConfiguration
, there’s also a backgroundConfiguration
that we can leverage to set background appearance properties and also a leadingSwipeActionsConfiguration
and trailingSwipeActionsConfiguration
to easily embed UITableView
-like swipe behavior directly in our UICollectionView
cell implementation.
The new UICollectionView.CellRegistration
structure that we just created automatically takes care of cell registration when passed inside the dequeueConfiguredReusableCell
. You don’t need to register cells using identifiers anymore.
#ios #programming #xcode #mobile #swift