1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

UICollectionViewDiffableDataSourceを使ってコレクションビューを実装する

Last updated at Posted at 2023-02-15

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)

以上です。

参考

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?