在iPhone的每次点击按钮时更改视图的背景颜色

时间:2012-11-20 13:04:18

标签: iphone objective-c uicolor

-(IBAction) changeColOnClick:(id)sender
{
    NSArray *colors = [NSArray arrayWithObjects:@"[UIColor brownColor]",@"[UIColor blackColor]",@"[UI greenColor]",@"[UIColor redColor]", nil];

    self.view.backgroundColor = [colors objectAtIndex:i];
    // ERROR::changebackground[1089:207] -[NSCFString CGColor]: unrecognized selector sent to instance 0x357c

    //label.text = [colors objectAtIndex:i]; //i is defined in the implementation
    i++;

    if(i==[colors count]-1)
    {
        i=0;
    }
}

6 个答案:

答案 0 :(得分:2)

您的代码崩溃了,因为您将字符串保存到数组中。尝试将实际颜色保存到数组中,如下所示:

NSArray *colors = [NSArray arrayWithObjects:[UIColor brownColor], [UIColor blackColor], [UIColor greenColor], [UIColor redColor], nil];

self.view.backgroundColor = [colors objectAtIndex:i];

如果这仍然不起作用,您可能需要以下内容:

self.view.backgroundColor = ((UIColor *)[colors objectAtIndex:i]).CGColor;

答案 1 :(得分:2)

@"[UIColor brownColor]"中的{p> array类型为NSString,而非UIColor

所以array应该是这样的:

 NSArray *colors = [NSArray arrayWithObjects:[UIColor brownColor],[UIColor blackColor],[UI greenColor],[UIColor redColor], nil];

MutableArray添加像这样的单个实例:

 [colors addObject:[UIColor blackColor]];

等等:

答案 2 :(得分:2)

像这样修改你的代码。它会起作用

-(IBAction) changeColOnClick:(id)sender
{
    NSArray *colors = [NSArray arrayWithObjects:[UIColor brownColor],[UIColor blackColor],[UI greenColor],[UIColor redColor], nil];

    self.view.backgroundColor = [colors objectAtIndex:i];
    //label.text = [colors objectAtIndex:i]; //i is defined in the implementation
    i++;

    if(i==[colors count]-1)
    {
        i=0;
    }
 }

答案 3 :(得分:1)

将颜色添加到数组中,如字符串对象。那是不对的。 你应该这样做:

[colors addObject:[UIColor blackColor]];
[colors addObject:[UIColor redColor]];

等等

答案 4 :(得分:1)

嘿,我只是测试你的代码而你只是这样设置你的方法: -

int i;
-(IBAction) changeColOnClick:(id)sender
{

    NSArray *colors = [NSArray arrayWithObjects:@"redColor",@"blackColor",@"greenColor",@"redColor", nil];


    NSString *str =[colors objectAtIndex:i];
    i++;
   //DARK_BACKGROUNDNavigation=str;

    SEL blackSel = NSSelectorFromString(str);
    UIColor* tColor = nil;
    if ([UIColor respondsToSelector: blackSel])
        tColor  = [UIColor performSelector:blackSel];
    [self.view setBackgroundColor:tColor];

    if(i==[colors count]-1){i=0;}
}

其工作愉快的编码:)

下载其演示

http://www.sendspace.com/file/9e68jx

答案 5 :(得分:1)

您已将数组中的对象作为字符串,因此它提供了数组。你必须采取UIColor类型obects ..

    UIColor *color1 = [UIColor brownColor];
    UIColor *color2 = [UIColor blackColor];
    UIColor *color3 = [UIColor greenColor];
    UIColor *color4 = [UIColor redColor];
    NSArray *colors = [NSArray arrayWithObjects:color1,color2,color3,color4, nil];
    self.view.backgroundColor = [colors objectAtIndex:i];