Pregunta

I have a .plist file, containing an array with dictionaries where each entry has a key-value-pair "color1:abc" and "color2:xyz". "abc" and "xyz" are always the standard iOS colors like "redColor" or "yellowColor" and so on.

My app has the "activeItem" from the .plist array and I want to set the color1 and color2 to the background of a view, so I tried something like:

self.view.backgroundColor = [UIColor [activeItem color2]];

(instead of: self.view.backgroundColor = [UIColor redColor];)

But that doesn't work... which syntax would be correct?

¿Fue útil?

Solución

If [activeItem color2] returns a method name (redColor, yellowColor and so on), you can use performSelector:

SEL selector = NSSelectorFromString([activeItem color2]); 
self.view.backgroundColor = [UIColor performSelector:selector];

Otros consejos

You'd have to implement a method that interprets the string value and returns the corresponding color.

UIColor *colorWithName: NSString *name
{
   if ([@"redColor" isEqualToString: name])
      return [UIColor redColor];
   else if (...)
      ...
}

Or put the named colors into an NSDictionary called namedColors and then just look them up by name.

Create class category.

create customColor.h file, for example:

@interface UIColor (customColor)

+(UIColor*)color1;
+(UIColor*)color2;

@end

@implementation UIColor (customColor)

+(UIColor*)color1
{
    return [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0];
}

+(UIColor*)color2
{
    return [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0];
}

@end

Then you can just use:

#import customColor.h
...
UIColor *neededColor = [UIColor color1];
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top