UIConfigurationColorTransformer 如何工作?
How does a UIConfigurationColorTransformer work?
Apple 说:
Because color transformers can use the same base input color to produce a number of variants of that color, you can create different appearances for different states of your views.
好的。我想尝试使用新的 iOS 14 backgroundConfiguration
架构而不是设置单元格的 backgroundView
和 selectedBackgroundView
。我希望我的 UITableViewCell 通常具有蓝色背景,但在被选中时具有灰色背景。所以,在我的 cellForRowAt
实现中:
var b = UIBackgroundConfiguration.listPlainCell()
b.backgroundColor = .blue
cell.backgroundConfiguration = b
到目前为止,还不错;细胞是蓝色的。但是灰色呢?这是我希望彩色转换器发挥作用的地方:
var b = UIBackgroundConfiguration.listPlainCell()
b.backgroundColor = .blue
b.backgroundColorTransformer = // what?
cell.backgroundConfiguration = b
颜色变换器是一个接受颜色和 returns 颜色的函数。通过记录,我可以看到每次单元格状态发生变化时,实际上都会调用颜色变换器函数。但是函数本身不带状态。它无权访问单元格的状态。那么,我该如何像 Apple 声称的那样“为不同的状态创建不同的外观”呢?
据我所知,答案分为两部分:
您正在 cellForRowAt
中配置后台配置,因此您具有对单元格的引用,因此具有对单元格配置状态的引用。
如果显式设置后台配置的backgroundColor
,则无法通过backgroundColorTransformer
设置。这是一个或另一个。 (我觉得这有问题,但无所谓。)
所以,下面是我想要的:
var b = UIBackgroundConfiguration.listPlainCell()
b.backgroundColorTransformer = UIConfigurationColorTransformer { [weak cell] c in
if let state = cell?.configurationState {
if state.isSelected || state.isHighlighted {
return .gray
}
}
return .blue
}
cell.backgroundConfiguration = b
Apple 说:
Because color transformers can use the same base input color to produce a number of variants of that color, you can create different appearances for different states of your views.
好的。我想尝试使用新的 iOS 14 backgroundConfiguration
架构而不是设置单元格的 backgroundView
和 selectedBackgroundView
。我希望我的 UITableViewCell 通常具有蓝色背景,但在被选中时具有灰色背景。所以,在我的 cellForRowAt
实现中:
var b = UIBackgroundConfiguration.listPlainCell()
b.backgroundColor = .blue
cell.backgroundConfiguration = b
到目前为止,还不错;细胞是蓝色的。但是灰色呢?这是我希望彩色转换器发挥作用的地方:
var b = UIBackgroundConfiguration.listPlainCell()
b.backgroundColor = .blue
b.backgroundColorTransformer = // what?
cell.backgroundConfiguration = b
颜色变换器是一个接受颜色和 returns 颜色的函数。通过记录,我可以看到每次单元格状态发生变化时,实际上都会调用颜色变换器函数。但是函数本身不带状态。它无权访问单元格的状态。那么,我该如何像 Apple 声称的那样“为不同的状态创建不同的外观”呢?
据我所知,答案分为两部分:
您正在
cellForRowAt
中配置后台配置,因此您具有对单元格的引用,因此具有对单元格配置状态的引用。如果显式设置后台配置的
backgroundColor
,则无法通过backgroundColorTransformer
设置。这是一个或另一个。 (我觉得这有问题,但无所谓。)
所以,下面是我想要的:
var b = UIBackgroundConfiguration.listPlainCell()
b.backgroundColorTransformer = UIConfigurationColorTransformer { [weak cell] c in
if let state = cell?.configurationState {
if state.isSelected || state.isHighlighted {
return .gray
}
}
return .blue
}
cell.backgroundConfiguration = b