3

我正在尝试用新的 iOS 14 UIListContentConfiguration 和 UIBackgroundConfiguration 替换我的 UITableViewCell 配置,但我不知道如何执行最基本的自定义。

例如,我有一个测试单元格,在我的数据源cellForRowAt:中,我正在像这样配置背景:

let v = UIImageView(image: UIImage(named:"linen.png"))
v.contentMode = .scaleToFill
cell.backgroundView = v

let v2 = UIView()
v2.backgroundColor = UIColor.blue.withAlphaComponent(0.2)
cell.selectedBackgroundView = v2

这个想法是我们有一个图像作为单元格的背景,当用户点击单元格以选择它时,我们用透明的蓝色色调覆盖它。选择单元格时,它selectedBackgroundView位于前面。backgroundView

好的,那么我该如何使用 UIBackgroundConfiguration 呢?我看到如何配置背景视图:

var back = UIBackgroundConfiguration.listPlainCell()
let v = UIImageView(image: UIImage(named:"linen.png"))
v.contentMode = .scaleToFill
back.customView = v
cell.backgroundConfiguration = back

但是当有选择时会发生什么呢?没有selectedCustomView,而且我在这里看不到针对不同州的不同背景的任何规定。

4

1 回答 1

3

以下似乎是您应该做的。在cellForRowAt:中,不是配置背景视图,而是告诉单元格不要自动更新其背景:

cell.automaticallyUpdatesBackgroundConfiguration = false

这意味着:我有一个自定义单元子类,它覆盖updateConfiguration(using:),我希望您在需要后台配置时调用该覆盖。

好的,现在就这样做。在您的单元子类中,覆盖updateConfiguration(using:). 在该覆盖中,执行您在 中所做的任何事情cellForRowAt:,但现在您可以考虑当前状态。没有selectedCustomView,所以只是做或不将选择色调覆盖在customView自身之上:

class MyCell : UITableViewCell {
    override func updateConfiguration(using state: UICellConfigurationState) {
        var back = UIBackgroundConfiguration.listPlainCell().updated(for: state)
        let v = UIImageView(image: UIImage(named:"linen.png"))
        v.contentMode = .scaleToFill
        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
    }
}

这按预期工作。当单元格被选中时,它具有蓝色色调;如果不是,则不是。

乍一看,为此必须创建一个单元子类似乎很疯狂。但事实上,这就是重点。这种基于配置的新架构的整个理念是,详细配置单元格的视图特性从来都不是数据源 ( ) 的业务。从数据源的角度来看,配置应该是轻量级的。单元担心配置在其子视图方面的含义。cellForRowAt

于 2020-07-23T22:35:48.510 回答