In iOS15, we have an efficient way to update items cell, by using reconfigureItems
.
Here's the code snippet to perform such efficient update.
Update items cell efficiently using reconfigureItems
private func reconfigureRecordingRow(_ recording: Recording) {
var snapshot = dataSource.snapshot()
snapshot.reconfigureItems([recording])
dataSource.apply(snapshot)
}
private func makeDataSource() -> DataSource {
let dataSource = DataSource(
collectionView: collectionView,
cellProvider: { [weak self] (collectionView, indexPath, anyHashable) -> UICollectionViewCell? in
guard let self = self else { return nil }
guard let recordingCell = collectionView.dequeueReusableCell(
withReuseIdentifier: "recording",
for: indexPath) as? RecordingCell else {
return nil
}
When reconfigureRecordingRow
is called, cellProvider's function will be executed.
collectionView.dequeueReusableCell
is able to re-use existing UICollectionViewCell
, without constructing new UICollectionViewCell
However, I was wondering, how can I achieve a similar efficiency, if I have a section, with header supplementary view, and without any item? For instance
Not able to update supplementary view efficiently
private func reloadAttachmentRow() {
var snapshot = dataSource.snapshot()
let sectionIdentifiers = snapshot.sectionIdentifiers
if sectionIdentifiers.contains(.attachment) {
snapshot.reloadSections([.attachment])
} else {
snapshot.insertSections([.attachment], beforeSection: .title)
}
dataSource.apply(snapshot)
}
dataSource.supplementaryViewProvider = { [weak self] collectionView, kind, indexPath in
guard let self = self else { return nil }
if kind == UICollectionView.elementKindSectionHeader {
let section = indexPath.section
let sectionIdentifier = self.sectionIdentifier(section)
switch sectionIdentifier {
case .attachment:
guard let collageViewHeader = collectionView.dequeueReusableSupplementaryView(
ofKind: kind,
withReuseIdentifier: "attachment",
for: indexPath) as? CollageViewHeader else {
return nil
}
When reloadSections
is called, dataSource.supplementaryViewProvider
will be executed.
As per my testing, collectionView.dequeueReusableSupplementaryView
will return a new instance of UICollectionReusableView
each time.
As a result, I can visually observe the entire section is "flickering", when reloadAttachmentRow
is called.
I was wondering, how can we update supplementary view efficiently?