UICollectionView loses selection when traitCollection changed

I have defined a UICollectionView using UICollectionViewDiffableDataSource, and each cell is a custom subclass of UICollectionViewCell. When the cell is selected, I use the isSelected var to change the background color of the cell.

Code Block
dataSource = UICollectionViewDiffableDataSource
<SectionType, CJSidebarFilterItem>(collectionView: collectionView) {
(collectionView: UICollectionView, indexPath: IndexPath, sidebarItem: CJSidebarFilterItem) -> UICollectionViewCell? in
guard let sidebarCell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as? CJSidebarCollectionViewCell else { fatalError("Could not create new cell")}
sidebarCell.countLabel?.text = countString
sidebarCell.titleLabel?.text = titleString
sidebarCell.filterImage?.image = itemImage
return sidebarCell
}
}


In SidebarCollectionCell

Code Block override var isSelected: Bool {
didSet {
if self.isSelected {
backgroundColor = .systemGray3
}
else {
backgroundColor = .secondarySystemGroupedBackground
}
}
}



It works fine for the most part, but when Dark Mode is activated (and hence traitCollectionDidChange is called), the cells lose their selection background color. I checked that the collectionView itself still has the 'indexPathsForSelectedItems' with the correct indexPaths. But for some reason, the cell's isSelected is false, so it looks like it's un-selected.

I called collectionView.reloadData() on traitCollectionDidChange but that didn't help. I've also tried setting the backgroundColor (based on cell.isSelected) inside the datasource configuration. Neither options helped.


Any clues as to what explains this, and what to try?
Turns out, due to some sizing issues, I was already calling collectionView.reloadData() inside viewWillLayoutSubviews() ... when I remove that line, the selection issue goes away.
Calling reloadData on the collection view will clear any selected index paths. You should avoid reloadData if possible, and instead apply new snapshots to your diffable data source to update the UI. If you do need to call reloadData or apply a snapshot with animatingDifferences: false, you need to manually re-select the items afterwards if desired.
UICollectionView loses selection when traitCollection changed
 
 
Q