3

我有一组这样的 NSString 值:

self.dataArray = @[@"blue", @"orange", @"green", @"red", @"yellow"];

并希望能够做类似的事情(在将上述颜色之一设置为 self.colorString 之后):

self.view.backgroundColor=[UIColor self.colorString + Color];

但显然不能这样做。什么是可能的方法?

4

3 回答 3

7

一种几乎通用的方式:

NSDictionary *colors = @{
    @"red": [UIColor redColor],
    @"green": [UIColor greenColor],
    @"blue": [UIColor blueColor]
};

NSString *name = @"blue";
UIColor *c = colors[name];

一种真正通用的方式:

NSString *selName = [NSString stringWithFormat:@"%@Color", name];
SEL sel = NSSelectorFromString(selName);
UIColor *color = [[UIColor class] performSelector:sel];
于 2013-08-03T05:50:05.067 回答
2

你可以尝试这样的事情:

SEL myColor = NSSelectorFromString([NSString stringWithFormat:@"%@Color", self.colorString]);
self.view.backgroundColor = [[UIColor class] performSelector:myColor]
于 2013-08-03T05:51:30.407 回答
1

尝试将您的数据与字典中的颜色相关联:

UIColor *blue = [UIColor blueColor];
UIColor *red = [UIColor redColor];

NSDictionary *colors = @{@"blue" : blue, @"red" : red};

UITextField *pinga = [[UITextField alloc]init];

pinga.textColor = [colors objectForKey:@"red"];
于 2013-08-03T05:50:01.993 回答