Xander
Xander

Reputation: 932

How to convert NSString to UIColor

I have a pickerView which has a component of colors.

I have a textField (textOther), now I have NSMutableArray of all the available colors which are explicitly defined.

How do I pass all those colors(which are strings!) to these textField?

textField setTextColor will set only a single color, but to pass string to a color how do I do it?

Thanks!

Upvotes: 3

Views: 5162

Answers (3)

fff
fff

Reputation: 3909

To convert from NSString to UIColor:

NSString *redColorString = @"25";
NSString *greenColorString = @"82";
NSString *blueColorString = @"125";

UIColor *color = [UIColor colorWithRed:[redColorString floatValue]/255.0
                                 green:[greenColorString floatValue]/255.0
                                  blue:[blueColorString floatValue]/255.0
                                 alpha:1.0];

Upvotes: 1

Aitul
Aitul

Reputation: 2992

It´s better to create a method to convert for NSString to UIColor. You shoud have a NSString with for example whiteColor or blueColor and you can convert it in the following way:

  -(UIColor *)getColor:(NSString*)col

  {

  SEL selColor = NSSelectorFromString(col);
  UIColor *color = nil;
  if ( [UIColor respondsToSelector:selColor] == YES) {

    color = [UIColor performSelector:selColor];
   }  
    return color;
  }

Upvotes: 8

RDM
RDM

Reputation: 5066

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.

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];

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!

Upvotes: 0

Related Questions