我最近使用了带有 Diffable DataSource 的 Compositional Layouts。我已经使用 UICollectionLayoutListConfiguration(appearance: .sidebar) 实现了侧边栏。我想将集合单元格选择颜色更改为自定义颜色。我使用了以下代码。
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
}
虽然它应用了选择颜色,但默认的单元格配置被覆盖了。有没有其他方法可以更改选择颜色
最佳答案
如果您已经在对单元格进行子类化,那么 updateConfiguration(using:) 绝对是要走的路。但是仅仅为了根据状态更改背景颜色而必须进行子类化似乎有点过分。有一种方法可以使用配置的 backgroundColorTransformer 属性在单元格的注册中正确执行此操作。就是这样:
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
如果选中或突出显示,这会将单元格的背景设置为灰色,否则将清除。归功于此 article .
关于ios - 如何在 CollectionView 的组合布局中更改选择颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63311717/