iOS14 collection view modern cell and diff datasource
一、前言:
在iOS14,CollectionView新增了一些API,讓開發者可以捨棄舊的delegate、datasource方式來實作,這些API分別負責處理Layout、Datasource跟Cell:
1. Lists: 新增在CompostionalLayouts,可以在CollectionView裡實現類似tableView的樣子。
2. CellRegistration:提供新的方式來讓開發者設計Cell,另外還有一個UICollectionViewListCell class,可以在預設的狀態下讓Cell有列表的樣式。
3. Diffable Data Soucre:包含Section Snapshots,可以以每個Section為基礎來更新資料。
二、實作:
1.註冊Cell的方法
在iOS14,開發者不用直接在Cell上設定屬性,新的API讓開發者可以直接設定cell的內容與樣式,依據不同狀態來更新資料
基本上看起來像這樣:
let cellRegistration = UICollectionView.CellRegistration<UICollectionViewCell, String> {cell, indexPath, name in
var content = UIListContentConfiguration.cell();
content.text = name;
cell.contentConfiguration = content;
};
而在UICollectionViews中,有個新的樣式,UICollectionViewListCell,用以下方式來實作:
let listCellRegistration = UICollectionView.CellRegistration<UICollectionViewListCell, String> {listCell, indexPath, name in
var content = listCell.defaultContentConfiguration();
content.text = name;
listCell.contentConfiguration = content;
};
這樣就可以不需使用以前的Cell identifiers,以及註冊Cell使用的if let或guard let來檢查cell是否存在。
在使用新的作法後,開發者不直接存取Cell的Label和Image,這樣可以建構出TableView、CollectionView與custom cell都可以使用的配置。
除了contentConfiguration外,也可用backgroundConfiguration設定背景的屬性,此外,還有leadingSwipeActionsConfiguration和trailingSwipeActionsConfiguration,從字面上就可以看出,可以在collectionView上做到與tableView一樣的左右滑動動作。
在建立了新的UICollectionView.CellRegistration後,會將資訊傳送到dequeueConfigureReusableCell自動註冊Cell,所以不需另外設定identifiers來註冊Cell。
2.list layout
要設定UICollectionViewListCell,需要傳入UICollectionViewListCellConfigurtion,除了預設的plain外,還有grouped、insetGroupsd、sideBar、sidebarPlain可以選擇:
let configuration = UICollectionLayoutListConfiguration(appearance: .plain);
let layout = UICollectionViewCompositionalLayout.list(using: configuration);
另外Lists的好處,就是支援self-sizing cell了,與tableView一樣cell可以根據內容自動調整大小。
如果要設定list的header與footer,在Configuration時設定headerMode和footerMode
config.headerMode = .supplementary;
config.footerMode = .supplementary;
接下來,需要呼叫Diffable data source的supplementaryViewProvider來提供view。
我實做了全部的config後,結果如下模擬器截圖:
三、結論:
1. iOS14新的CellRegistration,不需要使用舊的註冊方式來註冊Cell。
2. 新的API封裝了Cell的內容與背景的view屬性,UICollectionViewListCell提供一種預設的樣式,開發者可以根據需求做調整。
3. 在設定Cell時,開發者可以直接做客製設定,不需另外在Cell裡處理。
4. UICollectionView新的List可以像tableView一樣個別去處理section的header和footer。
有興趣可以下載demo code,記得需使用Xcode 12來執行。
https://drive.google.com/file/d/1LLb1Yql6eGCCzbIsgpvJwQqeEKBROfby/view?usp=sharing