UITableView Diffable Data Source
Introduction
- Diffable Data Source: A way to supply an object to UITableView or UICollectionView allowing model/data diffing and UI updates with animations.
- Automatically applies a snapshot to update data/UI.
Setup
- Create a New Project
- Use App template, name it
DiffableDataSource
, use Swift, Storyboard, and UIKit.
- Embed Navigation Controller
- Use Editor -> Embed in -> Navigation Controller in Storyboard.
Creating the Table View
- Anonymous closure pattern to initialize the table view.
- Register cell:
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
.
- Set
delegate = self
(No need to assign dataSource
here).
Diffable Data Source Initialization
- Create Models
- Section using enum.
- Data model (
Fruit
) using struct conforming to Hashable
.
- Declare Diffable Data Source
var dataSource: UITableViewDiffableDataSource<Section, Fruit>?
Adding UI Elements
- Add Plus Button
- Navigation bar button to add items.
- Present Action Sheet
UIAlertController
with multiple options to select and add fruits to the table view.
Snapshot
- Create and apply snapshot to data source:
var snapshot = NSDiffableDataSourceSnapshot<Section, Fruit>()
snapshot.appendSections([.main])
snapshot.appendItems(fruits, toSection: .main)
dataSource.apply(snapshot, animatingDifferences: true)
Handling Data Updates
- Button Action
- Append selected fruit to the data array and update the data source.
- Implement
updateDataSource
method
- Apply snapshot to update table view with animations.
Selection Handling
- Implement
UITableViewDelegate
method:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if let fruit = dataSource.itemIdentifier(for: indexPath) {
print(fruit.title)
}
}
Important Notes
- Ensure models are hashable and unique to avoid crashes.
- Diffable Data Source simplifies code, removing the need for
reloadData
calls.
- iOS 13 and up only.
Conclusion
- Simplifies updating UIs and handling data changes.
- Automatically handles animations for data changes.
Action Items
- Like, comment, subscribe for daily Swift updates!