[Swift] Compositional Layout - DiffableDataSource 와 함께 사용
Modern Collection View 와 MVVM 패턴 가이드
[iOS] Swift Modern Collection View & MVVM 패턴 가이드 강의 - 인프런
MVVM 패턴과 Modern Collection View를 사용해 네트워킹을 구현하고, 다양하고 동적인 Collection View를 자유자재로 다룰 수 있게 됩니다., Swift iOS UI, 제대로 다루는 핵심 기술! 📲 iOS Swift 레이아웃 구현을
www.inflearn.com
기존 datasource 구조에서 data controller 와 UI 가 상호작용하면 서 collectionview가 구성되는데
시간이 지남에따라 외부적인 변동으로 인해 controller가 가진 “Truth”와 UI가 가진 “Truth”가 맞지 않게되면 에러가 발생한다.
(Truth가 뭔지 정확하지 않지만 우선 상태라고 생각)
그래서 reloadData() 를 실행하면 해결 되지만 UX로 좋지않다 (애니메이션 적용 안됨)
이를 해결하기 위해 중앙화된 Truth를 사용한다.
DiffableDataSource 생성
diffableDatasource는 제너릭 클래스이다.
open class UICollectionViewDiffableDataSource<SectionIdentifierType, ItemIdentifierType> : NSObject, UICollectionViewDataSource where SectionIdentifierType : Hashable, ItemIdentifierType : Hashable {
제너릭은 SectionIdentifierType, ItemIdentifierType 으로 되어있고 둘다 Hashable을 채택해야한다.
init함수는 이렇다.
public init(collectionView: UICollectionView, cellProvider: @escaping UICollectionViewDiffableDataSource<SectionIdentifierType, ItemIdentifierType>.CellProvider)
public typealias CellProvider = (_ collectionView: UICollectionView, _ indexPath: IndexPath, _ itemIdentifier: ItemIdentifierType) -> UICollectionViewCell?
escaping 클로저로 Cellprovider 가 들어있고
CellProvider는 아래와 같은 구조로 되어있다.
해당 CellProvider 에서 cell을 리턴해주면 된다.
어떤 특정 이벤트에 의해서 datasource가 변경되어야할때
스냅샷을 바꿔서 적용시켜줘야한다.
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
snapshot.appendSections([.sectionType1])
snapshot.appendItems(items)
dataSource.apply(snapshot, animatingDifferences: false)
위와 같이 빈 스냅샷을 만든후 섹션&아이템을 추가후
apply()해주면 중앙화된 Truth가 변경되고 UI가 바뀐다.