Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How change the Selection Color in Compositional Layouts in CollectionView

Tags:

ios

swift

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

like image 908
Hash htk Avatar asked Mar 02 '23 04:03

Hash htk


2 Answers

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.

like image 168
Phantom59 Avatar answered Mar 04 '23 21:03

Phantom59


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
    }
}
like image 36
matt Avatar answered Mar 04 '23 22:03

matt