配色方案的Swift扩展和枚举 [英] Swift extension and enum for color schemes
问题描述
我使用以下代码块在空白的swift文件中创建枚举,以管理我的App中的配色方案:
I create enum in blank swift file for manage color Schemes in my App with this block of code:
enum Color {
case border
case waterMelon
case bleu
case ufoGreen
case lightBlue
}
最后,我基于刚刚创建的Color
枚举创建了一个扩展.
In the bottom of that I created a extension base on Color
enum I just made.
这里是扩展名:
extension Color {
var value: UIColor {
var instanceColor = UIColor.clear
switch self {
case .border:
instanceColor = UIColor(red:0.92, green:0.93, blue:0.94, alpha:1.00)
case .waterMelon:
instanceColor = UIColor(red:0.97, green:0.38, blue:0.45, alpha:1.00)
default:
instanceColor = UIColor.clear
}
return instanceColor
}
}
现在的问题是,当我想使用那些颜色时,我应该使用这样的颜色:
Now the problem is when I wanna use those color I should used something like this:
//now : I don't like it.
view.backgroundView = Color.dark.value
//that how I want to be
view.backgroundView = Color.dark
// or like this
view.backgroundView = .dark
我知道这是因为我在extension上声明的value
.但是我该如何摆脱呢?
And I know it's because of the value
that i declare on extension . but how can I get rid of that?
推荐答案
然后不要使用枚举.如果您不想枚举switch语句中的值,则不需要enum
.使用具有恒定属性的struct
.
Don't use an enum then. If you don't want to enumerate on the values in a switch statement, there is no need for an enum
. Use a struct
with constant attributes.
struct Color {
static let border = UIColor(red:0.92, green:0.93, blue:0.94, alpha:1.00)
static let waterMelon = UIColor(red:0.97, green:0.38, blue:0.45, alpha:1.00)
// and so on ....
}
如果您想扩展UIColor以访问UIColor的所有其他颜色,则可以如下扩展UIColor:
If you want to extend UIColor to have access to all the other colors of UIColor as well, you can extend UIColor like this:
extension UIColor {
static var border: UIColor {
return UIColor(red:0.92, green:0.93, blue:0.94, alpha:1.00)
}
static var waterMelon: UIColor {
return UIColor(red:0.97, green:0.38, blue:0.45, alpha:1.00)
}
}
这篇关于配色方案的Swift扩展和枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!