Reputation: 9
In (iOS) SWIFT I want to pass the label color via a variable and specifically an array. 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:
instead of
myLabel.textColor = UIColor.green
// Swift requires explicit definition of color "green"
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"...
Is there any other way around?
Upvotes: 0
Views: 632
Reputation: 420
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]
Upvotes: 0
Reputation: 157
Create an array of UIColor
not strings
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:
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"]
Upvotes: 0
Reputation: 1611
var Tcolor = [UIColor.green, UIColor.blue, UIColor.red]
See your error Tcolor is not a UIColor member
. your Tcolor is string
while myLabel.textColor
needs UIColor
Upvotes: 2