我正在尝试根据当前颜色更改 UIView
的 backgroundColor
。例如。说 MyView 现在是红色的,触摸时我想让它变成蓝色,反之亦然。但我注意到我无法获得 UIColor
的正确名称来检查当前颜色。
举个例子,如果我这样做:
if MyView.backgroundColor == .systemRed {
print("Red")
} else {
print("Not red")
}
即使我明确设置了 MyView.backgroundColor = .systemRed
当我检查正在使用的颜色时:
print("Color = \(MyView.backgroundColor)")
它打印:[...] name = systemRedColor
但是当我将 .systemRed
更改为 .systemRedColor
时,它给出了错误
'systemRedColor' has been renamed to 'systemRed'
我又回到了起点。
谁能告诉我我错过了什么?如何正确读取和设置 UIView
的 backgroundColor
?
最佳答案
.systemRed
是动态系统颜色之一,将根据 View 的当前特征条件.resolvedColor(with traitCollection:)
函数访问当前颜色。
在Light Mode下,systemRed
会显示为:
UIExtendedSRGBColorSpace 1 0.231373 0.188235 1
R255 G59 B48
在深色模式下,systemRed
将显示为:
UIExtendedSRGBColorSpace 1 0.270588 0.227451 1
R255 G69 B58
if view.backgroundColor?.resolvedColor(with: view.traitCollection) == UIColor.systemRed.resolvedColor(with: view.traitCollection) {
print("true")
}
这将适用于动态和标准的 UIColor
。
你也可以在 UIColor
上做一个扩展来做到这一点
extension UIColor {
class func compare(_ colorA: UIColor?, with colorB: UIColor?, in view: UIView) -> Bool {
colorA?.resolvedColor(with: view.traitCollection) == colorB?.resolvedColor(with: view.traitCollection)
}
}
用法:
if UIColor.compare(self.view.backgroundColor, with: .systemRed, in: view) {
print("true")
}
关于ios - 如何正确获取和设置 UIView 的 UIColor?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61760182/