如何正确获取和设置UIView的UIColor?

问题描述 投票:0回答:3

我想改变一个 UIView's 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'

我又回到了起点。

谁能告诉我,我缺少什么?我如何正确读取和设置 backgroundColorUIView?

ios swift uicolor
3个回答
1
投票

.systemRed 是动态系统颜色之一,根据视图当前的特性条件不同,显示的颜色也不同 (即暗模式亮模式). 因此,你需要使用下面的命令来访问当前的颜色。.resolvedColor(with traitCollection:) 功能。

灯光模式, systemRed 将显示为:UIExtendedSRGBColorSpace 1 0.231373 0.188235 1R255 G59 B48。

黑暗模式, systemRed 将显示为:UIExtendedSRGBColorSpace 1 0.270588 0.227451 1R255 G69 B58。

if view.backgroundColor?.resolvedColor(with: view.traitCollection) == UIColor.systemRed.resolvedColor(with: view.traitCollection) {
    print("true")
}

这将适用于动态和标准的 UIColor's.


你也可以在 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")
}

0
投票

你可以试试这个:

self.bgView.backgroundColor = UIColor.red
 print("self.bgView.backgroundColor")

   if self.bgView.backgroundColor!.isEqual(UIColor.red){
      print("Red")
   } else {
   print("No Red")
 }
 print(self.bgView.backgroundColor)

/它将打印红色

© www.soinside.com 2019 - 2024. All rights reserved.