UICollectionView
について新しいAPIを使ってコレクションビューを実装するメモです。
UICollectionViewDiffableDataSource
はiOS 13で導入されたAPIであり、簡単な実装と高速なパフォーマンスを提供するデータソースです。
従来のUICollectionViewDataSource
と比較して、自動的にアニメーションを行い、アイテムを自動的に移動することができます。
使用例
以下の手順でUICollectionViewDiffableDataSource
を使用して、UICollectionView
を実装します。
データソース
UICollectionViewDiffableDataSource
のインスタンスを作成します。
let dataSource = UICollectionViewDiffableDataSource<Section, Item>(collectionView: collectionView) { collectionView, indexPath, item in
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CustomCell
cell.textLabel.text = item.title
return cell
}
スナップショット
UICollectionViewDiffableDataSource
のSnapshotを作成します。Snapshotには、セクションとアイテムの配列が含まれます。
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
snapshot.appendSections([.main])
snapshot.appendItems(items)
dataSource.apply(snapshot, animatingDifferences: true)
更新処理
データが変更された場合は、applyメソッドを使用してSnapshotを更新します。
var snapshot = dataSource.snapshot()
snapshot.deleteItems(deletedItems)
snapshot.appendItems(addedItems)
dataSource.apply(snapshot, animatingDifferences: true)
以上です。
参考