本文介绍了以某种方式将自定义.colorNames添加到UIColor?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我非常喜欢使用这样的颜色的快捷方式:

I quite like the shortcuts for using colours like this:

myLabel.fontColor = .gray

然后像这样制作自己的照片:

And making my own, like this:

static let fadedGreen = SKColor.init(hue: 0.33,
                                     saturation: 1,
                                     brightness: 0.33,
                                     alpha: 1.0)

但这需要调用我放入的类以使用缩写 fadedGreen 像这样:

But this requires calling the class I've put this in to use the abbreviation fadedGreen like this:

myLabel.fontColor = MyStorageClass.fadedGreen



问题:



有没有一种方法可以扩展或添加到(假设的)枚举预置中UIColor,这样我就可以制作自己的颜色,并且只需使用像这样的点:

myLabel.fontColour = .myCustomColor

...从我项目中的任何地方吗?

... from anywhere in my project?

这是否意味着SKColor .presets 也可以立即使用它们?

And will that mean that they're instantly available to SKColor .presets, too?

请原谅我对如何执行此操作的完全无知。

推荐答案

并不是真正的颜色快捷方式。那只是推断类型。 fontColor 属性的类型为UIColor,UIColor在 class 上具有一堆只读属性,它们是颜色名称并返回颜色对象。所以当你说

Those aren't really color shortcuts. That's just inferring a type. The fontColor property is typed as UIColor, and UIColor has a bunch of read-only properties on the class that are color names and return color objects. So when you say

myLabel.fontColor = .myCustomColor

点告诉它这是一个在某处的字段,猜猜在哪里,Swift走了,嗯,我需要一个 UIColor ,所以让我们看一下 UIColor 类是否具有返回正确类型的该名称的属性。

The dot tells it "it is a field somewhere, guess where" and Swift goes, well, I need a UIColor, so let's look if the UIColor class has properties of that name that return the right type.

要添加您自己必须在UIColor的扩展中定义颜色属性。

So to add your own, you'd have to define your color properties in an extension on UIColor.

extension UIColor {
    static let con_pink = UIColor( red: 1.0, green: 0.0, blue: 0.5, alpha: 1.0 )
}

和可以用作 myLabel.fontColor = .con_pink 的人。

但是请注意,如果这样做,可能会与Apple将来可能添加的任何颜色方法发生冲突。因此,我建议您在属性名称中添加前缀(我根据您的用户名为您选择了 con_),以减少Apple使用相同名称的可能性。

But note that, if you do this, you're risking collisions with any color methods Apple might add in the future. So I recommend that you add a prefix to the property names (I chose "con_" for you based on your username), to make it less likely that Apple use the same name.

这篇关于以某种方式将自定义.colorNames添加到UIColor?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 23:32