Reputation:
I have buttons filled with Colors: enter image description here
When user press on a color, a string is generated, i.e.
Yellow
or Blue
or Black
etc.
What i want is to load the string into a UIColor when i segue back:
garageNameLabel.backgroundColor = UIColor."THE STRING THAT WAS GENERATED"
I know that UIColor.whiteColor()
, blackColor()
is there.
code:
let theStringColor = Blue
garageNameLabel.backgroundColor = UIColor.theStringColor
Thanks
Upvotes: 1
Views: 1891
Reputation: 414
In OBJC code like this works. i have not tested this code, only translated it from OBJC to swift.
private func setColorWithNameForLabel(label: UILabel, colorName: String) {
let colorString = colorName + "Color" // if your colorName matches f.i. "black" --> blackColor
let s = Selector(colorString)
if let color = UIColor.performSelector(s).takeUnretainedValue() as? UIColor { // as of swift 2.0 you have to take the retained value
label.textColor = color
}
}
Upvotes: 2
Reputation: 326
You can pass a parameter in the segue. In the new view, in the viewDidLoad () function, you can perform a check that change color depending on the value of the parameter.
if parameter == "blue" {
garageNameLabel.backgroundColor = UIColor.blueColor ()
} Else if parameter == "green" {
garageNameLabel.backgroundColor = UIColor.greenColor ()
}
Upvotes: 0
Reputation:
I solved the problem by making a dictionary
var colors : [String:UIColor] = ["White": UIColor.whiteColor(), "Black":
UIColor.blackColor(), "Gray": UIColor.grayColor(),"Turquoise":
UIColor.cyanColor(),"Red":
UIColor.redColor(),"Yellow":UIColor.yellowColor(),"Blue": UIColor.blueColor(),
"Green": UIColor.greenColor()]
and then loading the string into it i.e.:
let theStringColor = "Blue"
garageNameLabel.backgroundColor = colors[theStringColor]
Upvotes: 5