- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试用新的 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 来做到这一点?我看到如何配置背景 View :
var back = UIBackgroundConfiguration.listPlainCell()
let v = UIImageView(image: UIImage(named:"linen.png"))
v.contentMode = .scaleToFill
back.customView = v
cell.backgroundConfiguration = back
但是当有选择时会发生什么?没有 selectedCustomView
,我在这里也没有看到针对不同状态的不同背景的任何规定。
最佳答案
以下似乎是您需要做的事情。在 cellForRowAt:
中,不配置背景 View ,而是告诉单元格不要自动更新其背景:
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
) 的业务来配置单元格的 View 详细的特点。从数据源的角度来看,配置应该轻量级。让 cell 考虑配置对其 subview 的意义。
关于ios - UITableViewCell中UIListContentConfiguration和UIBackgroundConfiguration的基本使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63057271/
我是一名优秀的程序员,十分优秀!