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.
In SidebarCollectionCell
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?
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?