我最近使用了具有 Diffable DataSource 的组合布局。我已经使用 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
}
Run Code Online (Sandbox Code Playgroud)
尽管它应用了选择颜色,但默认单元格配置被覆盖。还有其他方法可以更改选择颜色
如果您已经对单元格进行子类化,那么 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
Run Code Online (Sandbox Code Playgroud)
如果选择或突出显示,这会将单元格的背景设置为灰色,否则设置为清除。归功于这篇文章。
您必须使用一个单元格子类来在状态更改时更新其自己的背景。例子:
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
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3032 次 |
| 最近记录: |