How to convert NSString to UIColor

前端 未结 3 1680
Happy的楠姐
Happy的楠姐 2021-01-14 11:35

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 defin

相关标签:
3条回答
  • 2021-01-14 12:16

    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;
      }
    
    0 讨论(0)
  • 2021-01-14 12:20

    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];
    
    0 讨论(0)
  • 2021-01-14 12:22

    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!

    0 讨论(0)
提交回复
热议问题