如何将NSString转换为UIColor [英] How to convert NSString to UIColor
问题描述
我有一个pickerView,它有一个颜色组件。
I have a pickerView which has a component of colors.
我有一个textField(textOther),现在我有所有可用颜色的NSMutableArray,它们是明确定义的。
I have a textField (textOther), now I have NSMutableArray of all the available colors which are explicitly defined.
如何将所有这些颜色(字符串!)传递给这些textField?
How do I pass all those colors(which are strings!) to these textField?
textField setTextColor将只设置一种颜色,但要将字符串传递给颜色我该怎么做?
textField setTextColor will set only a single color, but to pass string to a color how do I do it?
谢谢!
推荐答案
我认为最简单的方法是使用预定义的 UIColor $制作
NSDictionary
c $ c>实例,并将它们映射为键值对; keys是表示颜色的字符串,value是实际的 UIColor
对象。
I suppose the cleanest way to do this would be by making an NSDictionary
with predefined UIColor
instances, and map them as key value pairs; keys being the string that represents the color, value being the actual UIColor
object.
所以如果你想要的话如果我理解的话,将红色和蓝色都作为可能的颜色(现在在 NSMutableArray
中),你可以制作一个 NSDictionary
像这样:
So if you'd want to have both red and blue as possible colors (which are now in an NSMutableArray
if I understood correctly), you'd make an NSDictionary
like this:
NSArray * colorKeys = [NSArray arrayWithObjects:@"red", @"blue" nil];
NSArray * colorValues = [NSArray arrayWithObjects:[UIColor redColor], [UIColor blueColor], nil];
NSDictionary * colorMap = [NSDictionary dictionaryWithObjects:colorValues forKeys:colorKeys];
如果你想传递一种颜色(给出一个字符串AKA所说颜色的键),你可以简单地这样做:
If you then want to pass a color (given a string AKA the key of said color), you can simply do this:
NSString * chosenColor = textField.text; // extract desired color from input in textField
textField.textColor = [colorMap valueForKey:chosenColor]; // use this color string to find the UIColor element in the colorMap
希望这能回答你的问题!
Hope this answers your question!
这篇关于如何将NSString转换为UIColor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!