如何正确获取和设置 UIView 的 UIColor? [英] How to correctly get and set UIColor for UIView?

查看:17
本文介绍了如何正确获取和设置 UIView 的 UIColor?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据其当前颜色更改 UIViewbackgroundColor.例如.说 MyView 现在是红色的,触摸时我想让它变成蓝色,反之亦然.但我注意到我无法获得 UIColor 的正确名称来检查当前颜色.

I'm trying to change a UIView's backgroundColor based on its current color. E.g. say MyView is now red, on touch I want to make it blue and vice versa. But I noticed I cannot get the correct name of the UIColor to check the current color.

举个例子,如果我这样做:

As an example, if I do:

if MyView.backgroundColor == .systemRed {
        print("Red")
    } else {
        print("Not red")
    }

即使我明确设置了 MyView.backgroundColor = .systemRed

当我检查正在使用的颜色时:

When I check the color being used:

print("Color = \(MyView.backgroundColor)")

它打印:[...] name = systemRedColor

但是当我将 .systemRed 更改为 .systemRedColor 时,它给出了错误

But when I change .systemRed to .systemRedColor, it gives the error

'systemRedColor' has been renamed to 'systemRed'

然后我又回到了起点.

谁能告诉我我错过了什么?如何正确读取和设置UIViewbackgroundColor?

Can anyone tell me what I am missing? How do I correctly read and set the backgroundColor of UIView?

推荐答案

.systemRed 是动态系统颜色之一,将根据视图的当前特征条件(即暗模式/亮模式).因此,您需要使用 .resolvedColor(with traitCollection:) 函数访问当前颜色.

.systemRed is one of the dynamic system colours that will be displayed differently depending on the view's current trait condition (i.e. Dark Mode / Light Mode). Therefore you need to access the current color using the .resolvedColor(with traitCollection:) function.

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

In Light Mode, systemRed will display as: UIExtendedSRGBColorSpace 1 0.231373 0.188235 1 R255 G59 B48

深色模式中,systemRed将显示为:UIExtendedSRGBColorSpace 1 0.270588 0.227451 1R255 G69 B58

In Dark Mode, systemRed will display as: 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.

This will work with both dynamic and standard UIColor's.

你也可以在 UIColor 上做一个扩展来做到这一点

You could also make an extension on UIColor to do this

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")
}

这篇关于如何正确获取和设置 UIView 的 UIColor?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆