mat*_*att 5 uitableview ios ios14
我正在尝试用新的 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
Run Code Online (Sandbox Code Playgroud)
我们的想法是,我们有一个图像作为单元格的背景,当用户点击单元格来选择它时,我们用透明的蓝色色调覆盖它。当单元格被选中时,位于selectedBackgroundView的前面。backgroundView
好的,那么我该如何使用 UIBackgroundConfiguration 来做到这一点呢?我看到如何配置背景视图:
var back = UIBackgroundConfiguration.listPlainCell()
let v = UIImageView(image: UIImage(named:"linen.png"))
v.contentMode = .scaleToFill
back.customView = v
cell.backgroundConfiguration = back
Run Code Online (Sandbox Code Playgroud)
但是当有选择时会发生什么呢?没有selectedCustomView,我在这里没有看到任何针对不同州的不同背景的规定。
以下似乎是您期望做的事情。在 中cellForRowAt:,不要配置背景视图,而是告诉单元格不要自动更新其背景:
cell.automaticallyUpdatesBackgroundConfiguration = false
Run Code Online (Sandbox Code Playgroud)
这意味着:我有一个自定义单元子类,它覆盖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
}
}
Run Code Online (Sandbox Code Playgroud)
这按预期工作。当单元格被选中时,它具有蓝色色调;如果不是,就不会。
乍一看,为此创建一个单元子类似乎很疯狂。但这实际上就是重点。这种新的基于配置的体系结构的整个理念是,详细配置单元的视图功能从来都不是数据源 () 的职责。从数据源的角度来看,配置应该是轻量级的。让单元关心配置对其子视图的含义。cellForRowAt
| 归档时间: |
|
| 查看次数: |
4468 次 |
| 最近记录: |