把string变成一个UIColor快速

我有充满颜色的button: enter image description here

当用户按一个颜色时,会产生一个string,即YellowBlueBlack等。

我想要的是加载到UIColor的string,当我继续:

 garageNameLabel.backgroundColor = UIColor."THE STRING THAT WAS GENERATED" 

我知道, UIColor.whiteColor()blackColor()在那里。

码:

 let theStringColor = Blue garageNameLabel.backgroundColor = UIColor.theStringColor 

谢谢

我用字典解决了这个问题

 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()] 

然后加载到它的string即:

 let theStringColor = "Blue" garageNameLabel.backgroundColor = colors[theStringColor] 

在像这样的OBJC代码工作。 我没有testing过这个代码,只是将它从OBJC转换成了swift。

 private func setColorWithNameForLabel(label: UILabel, colorName: String) { let colorString = colorName + "Color" // if your colorName matches fi "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 } } 

你可以在segue中传递一个参数。 在新视图中,在viewDidLoad()函数中,您可以执行检查,根据参数的值更改颜色。

 if parameter == "blue" { garageNameLabel.backgroundColor = UIColor.blueColor () } Else if parameter == "green" { garageNameLabel.backgroundColor = UIColor.greenColor () }