iOS13中UITableViewCell的默认背景色是什么?

What is the default background color of UITableViewCell in iOS 13?

UITableViewCell 的默认背景 UIColor 是什么?我需要一个常量 UIColor 对象而不是 RGB,因为我希望在 iOS 13 中实现暗模式。(我找不到任何匹配的颜色,例如 [UIColor systemBackgroundColor])。

我在willDisplayCell:forRowAtIndexPath:下了一个断点并打印了cell.backgroundColor。这是我得到的:

<UIDynamicSystemColor: 0x600000bf2c00; name = tableCellGroupedBackgroundColor>

这似乎是一个没有 public 等价物的私人 class。有什么关于如何定位这个的建议吗?

普通样式 table 视图中的单元格使用 UIColor.systemBackground[Color] 作为背景,UIColor.label[Color] 作为标题文本,UIColor.secondaryLabel[Color] 作为副标题文本。

对于分组样式 table 视图,单元格背景使用 UIColor.secondarySystemGroupedBackground[Color],table 视图背景使用 UIColor.systemGroupedBackground[Color].

所有这些都适应light/dark模式。

下面是一个有用的 UIColor 扩展,它允许您打印任何颜色的明暗描述。

extension UIColor {
    var lightDarkDescription: String {
        let lightTraits = UITraitCollection.init(userInterfaceStyle: .light)
        let darkTraits = UITraitCollection.init(userInterfaceStyle: .dark)
        let lightColor = self.resolvedColor(with: lightTraits)
        let darkColor = self.resolvedColor(with: darkTraits)
        if lightColor == darkColor {
            return self.description
        } else {
            return "\(self), light: \(lightColor), dark: \(darkColor)"
        }
    }
}

示例:

print(UIColor.secondarySystemGroupedBackground.lightDarkDescription)
print(UIColor.secondaryLabel.lightDarkDescription)
print(UIColor.green.lightDarkDescription)

输出:

<UIDynamicSystemColor: 0x6000005a5d80; name = secondarySystemGroupedBackgroundColor>, light: UIExtendedGrayColorSpace 1 1, dark: UIExtendedSRGBColorSpace 0.109804 0.109804 0.117647 1
<UIDynamicSystemColor: 0x6000005a5f00; name = secondaryLabelColor>, light: UIExtendedSRGBColorSpace 0.235294 0.235294 0.262745 0.6, dark: UIExtendedSRGBColorSpace 0.921569 0.921569 0.960784 0.6
UIExtendedSRGBColorSpace 0 1 0 1

如果有人想玩所有颜色,请查看我在 GitHub 上的 SystemColors 演示应用程序。

在iOS13中,为了支持深色模式,可以对单元格背景使用secondarySystemGroupedBackground

Swift代码:

if #available(iOS 13.0, *) {
    cellBackgroundColor = .secondarySystemGroupedBackground
} else {
    cellBackgroundColor = .white
}

相应的,组table查看背景,可以使用(primary)systemGroupedBackground.

新的语义颜色适用于组,包含其他组(主要 -> 次要 -> 第三),并且不限于 table 视图。这是完全有道理的。我写过它 here