简体   繁体   English

以编程方式在 Swift 中设置标签颜色

[英]Set Label Color in Swift Programmatically

In (iOS) SWIFT I want to pass the label color via a variable and specifically an array.在(iOS)SWIFT 中,我想通过一个变量,特别是一个数组来传递标签颜色。 I calculate a number (my index) and then I want to lookup inside an array which contains the color strings, select a color and pass it on to the UIColor part of the Label definition:我计算了一个数字(我的索引),然后我想在包含颜色字符串的数组中查找,选择一种颜色并将其传递给 Label 定义的UIColor部分:

instead of代替

myLabel.textColor = UIColor.green

// Swift requires explicit definition of color "green" // Swift 需要明确定义颜色“绿色”

I want我想要

var Tcolor = ["green", "blue", "red"]
var index: Int = 1

myLabel.text = "myLabel Text"

myLabel.textColor = UIColor.Tcolor[index]

//this should produce the same result as above but programmatically. //这应该产生与上面相同的结果,但以编程方式。 However, it然而,它

returns error with comment "Tcolor is not a UIColor member"...返回带有注释“Tcolor 不是 UIColor 成员”的错误...

Is there any other way around?有没有其他办法?

var Tcolor = [UIColor.green, UIColor.blue, UIColor.red]

See your error Tcolor is not a UIColor member .请参阅您的错误Tcolor is not a UIColor member your Tcolor is string while myLabel.textColor needs UIColor你的 Tcolor 是stringmyLabel.textColor需要UIColor

Create an array of UIColor not strings创建一个UIColor数组而不是字符串

var Tcolor : [UIColor] = [UIColor.red, UIColor.blue, UIColor.green]
var index: Int = 1
myLabel.textColor = Tcolor[index]

If you need Sting names for the colors you can do this:如果您需要颜色的 Sting 名称,您可以这样做:

Tcolor : [String : UIColor] = ["Red" : UIColor.red, "Blue" : UIColor.blue, "green" : UIColor.green]

Color by friendly name?按友好名称着色?

let Tcolor_red = Tcolor["Red"]

OR或者

myLabel.textColor = Tcolor["Red"]

You can try like this你可以这样试试

let colors = [UIColor(red:1.00, green:0.09, blue:0.32, alpha:1.0), UIColor(red:1.00, green:0.80, blue:0.02, alpha:1.0), UIColor(red:0.00, green:0.81, blue:0.62, alpha:1.0), UIColor(red:0.00, green:0.56, blue:0.00, alpha:1.0)]

myLabel.textColor = color[2]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM