Swift 中 UIView 和一般情况下的神秘 UIColor 行为

Mysterious UIColor behaviour with UIView and in General in Swift

最近我在 Swift..

中遇到了一个关于 UIColor 的有趣(可能是天真的)问题
import UIKit

let view = UIView(frame: CGRect(x: 0,
                                y: 0,
                                width: 50,
                                height: 50))
view.backgroundColor = .systemBlue

let a = UIColor.systemBlue
switch a {
case .red:
    print("red")
case .systemBlue:
    print("blue")
default:
    print("unknown")
}

以下代码在 playground 上打印 "blue" 非常好,但正在改变

let a = UIColor.systemBlue
to
let a = view.backgroundColor ?? .red

在操场上打印 "unknown",有人可以帮助解决这里发生的问题吗?我无法解决它。它在某些时候是否与值类型或引用类型相关?请帮忙!!

打印这两个值给你解释:

print(UIColor.systemBlue)

<UIDynamicSystemColor: 0x600000b47880;
  name = systemBlueColor
>
print(view.backgroundColor!)

<UIDynamicModifiedColor: 0x60000058bed0;
  contrast = normal,
  baseColor = <UIDynamicSystemColor: 0x600000b47880;
    name = systemBlueColor
  >
>

设置 backgroundColor 属性 时,UIKit 将颜色包装在私有 class UIDynamicModifiedColor.

如果您使用视图的特征比较解析的颜色,您将得到 true:

UIColor.systemBlue.resolvedColor(with: view.traitCollection) ==
  view.backgroundColor!.resolvedColor(with: view.traitCollection)

解析的颜色是绝对颜色:

print(UIColor.systemBlue.resolvedColor(with: view.traitCollection))

UIExtendedSRGBColorSpace 0 0.478431 1 1

UIColor.systemBlue 等颜色是一种动态颜色,可能会产生不同的颜色,具体取决于视图的特征,包括高对比度模式和 dark/light 模式等因素。

来自docs of UIColor.systemBlue

A blue color that automatically adapts to the current trait environment.