I have a set of NSString values like this:
self.dataArray = @[@"blue", @"orange", @"green", @"red", @"yellow"];
and would like to be able to do something like (after getting one of the above colors set to self.colorString):
self.view.backgroundColor=[UIColor self.colorString + Color];
but obviously can't do that. What is a possible way?
A nearly universal way:
NSDictionary *colors = @{
@"red": [UIColor redColor],
@"green": [UIColor greenColor],
@"blue": [UIColor blueColor]
};
NSString *name = @"blue";
UIColor *c = colors[name];
A truly universal way:
NSString *selName = [NSString stringWithFormat:@"%@Color", name];
SEL sel = NSSelectorFromString(selName);
UIColor *color = [[UIColor class] performSelector:sel];
You can try something like this:
SEL myColor = NSSelectorFromString([NSString stringWithFormat:@"%@Color", self.colorString]);
self.view.backgroundColor = [[UIColor class] performSelector:myColor]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With