I've recently worked with Compositional Layouts with Diffable DataSource. I've implemented side bar using UICollectionLayoutListConfiguration(appearance: .sidebar). I want to change the collection cell selection color to a custom color. I've used following code.
let cellRegistration = UICollectionView.CellRegistration<UICollectionViewListCell, MenuData> { (cell, indexPath, item) in
let red = UIView()
red.backgroundColor = UIColor.red
cell.selectedBackgroundView = red
var content = cell.defaultContentConfiguration()
content.text = item.menuTitle
content.image = item.image
cell.contentConfiguration = content
}
though it applys the selection color, default cell configuration got override. is there any other approch to change the selection color
If you're already subclassing a cell then updateConfiguration(using:) is definitely the way to go. But it seemed a bit excessive to have to subclass just to change the background color based on the state. There's a way to do it right in the cell's registration using the configuration's backgroundColorTransformer property. Here's how:
var background = UIBackgroundConfiguration.listSidebarCell()
background.backgroundColorTransformer = UIConfigurationColorTransformer { [weak cell] c in
guard let state = cell?.configurationState else { return .clear }
return state.isSelected || state.isHighlighted ? .gray : .clear
}
cell.backgroundConfiguration = background
This will set the cell's background to gray if selected or highlighted and clear otherwise. Credit goes to this article.
You have to use a cell subclass that updates its own background on a state change. Example:
class MyCell : UICollectionViewCell {
override func updateConfiguration(using state: UICellConfigurationState) {
var back = UIBackgroundConfiguration.listPlainCell().updated(for: state)
let v = UIView()
if state.isSelected || state.isHighlighted {
let v2 = UIView()
v2.backgroundColor = UIColor.blue.withAlphaComponent(0.2)
v.addSubview(v2)
v2.frame = v.bounds
v2.autoresizingMask = [.flexibleWidth, .flexibleHeight]
}
back.customView = v
self.backgroundConfiguration = back
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With