-
[Swift] Compositional Layout - DiffableDataSource 와 함께 사용개발/Swift 2022. 11. 23. 17:00
Modern Collection View 와 MVVM 패턴 가이드
기존 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가 바뀐다.
'개발 > Swift' 카테고리의 다른 글
외부 영역 터치시 키보드 사라지게 하는방법 in TableView (0) 2022.12.05 Compositional Layout + Diffable DataSource - 2 헤더 추가하기 (0) 2022.11.27 [Swift] Compositional Layout - 헤더, 다양한 layout적용 (0) 2022.11.23 [Swift] Compositional Layout - 레이아웃 그려보기 (0) 2022.11.22 Closure 의 Capture 와 Self (0) 2022.11.21