如何使用UIColor值创建Swift枚举? [英] How can I make a Swift enum with UIColor value?

查看:223
本文介绍了如何使用UIColor值创建Swift枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作绘图应用程序,我想通过枚举引用我的颜色。例如,使用 Colors.RedColor 会更清洁,更方便,而不是每次我想要红色时都键入值。但是,Swift的原始值枚举似乎并不接受UIColor作为一种类型。有没有办法用枚举或类似的方法做到这一点?

I'm making a drawing app and I would like to refer to my colors through use of an enum. For example, it would be cleaner and more convenient to use Colors.RedColor instead of typing out values every time I want that red color. However, Swift's raw value enums don't seem to accept UIColor as a type. Is there a way to do this with an enum or something similar?

推荐答案

我这样做(基本上使用结构体一个命名空间):

I do it like this (basically using a struct as a namespace):

extension UIColor {
  struct MyTheme {
    static var firstColor: UIColor  { return UIColor(red: 1, green: 0, blue: 0, alpha: 1) }
    static var secondColor: UIColor { return UIColor(red: 0, green: 1, blue: 0, alpha: 1) }
  }
}

您可以像这样使用它:

UIColor.MyTheme.firstColor

因此您可以在自定义主题中使用红色。

So you can have a red color inside your custom theme.

这篇关于如何使用UIColor值创建Swift枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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