0

可能重复:
如何将 nsstring 转换为 uicolor?

不是objective-c程序员,但不确定我是否不能做这样的事情。我知道我正在返回一个字符串值,但只是想要一种简洁的方式来获取这些值:

NSMutableArray *colorsArray=[[NSMutableArray alloc] init];
[colorsArray addObject:@"whiteColor"];
[colorsArray addObject:@"blueColor"];
 // val5 is either 0 or 1
[view setBackgroundColor:[UIColor [colorsArray objectAtIndex:val5]]];

这可能吗?

提前谢谢

4

3 回答 3

5

为什么不直接存储颜色而不是NSString

NSMutableArray *colorsArray=[[NSMutableArray alloc] init];
[colorsArray addObject:[UIColor whiteColor]];
[colorsArray addObject:[UIColor blueColor]];
if (val5 < colorsArray.count) // Doesn't hurt any to be safe, and this way you won't get a crash if something messes up your val5 at some point
{
    // val5 is either 0 or 1
    [view setBackgroundColor:[colorsArray objectAtIndex:val5]];
}
else
{
    NSLog(@"Error - Color not expected - leaving color the way it is.")
}

您按原样编写代码不会编译,语法无效,因为您尝试这样做[UIColor @"whiteColor"]不是有效的语法。您可以使用performSelector:,但这毫无意义,除非您真的需要将颜色存储为字符串。

于 2012-12-06T19:43:43.557 回答
3

或者,如果您必须使用NSString数组中的实例:

NSMutableArray *colorsArray=[[NSMutableArray alloc] init];
[colorsArray addObject:@"whiteColor"];
[colorsArray addObject:@"blueColor"];

SEL colorSelector = NSSelectorFromString([colorsArray objectAtIndex:val5]);
[view setBackgroundColor:[UIColor performSelector:colorSelector]];
于 2012-12-06T19:45:57.220 回答
2
NSMutableArray *colorsArray = [[NSMutableArray alloc] init];
[colorsArray addObject:@"whiteColor"];
[colorsArray addObject:@"blueColor"];
UIColor *color = [UIColor performSelector:NSSelectorFromString([colorsArray objectAtIndex:1])];
view.backgroundColor = color;
于 2012-12-06T19:45:38.523 回答