iOS数组颜色检索错误

时间:2012-06-08 01:37:44

标签: objective-c ios uiview colors

我正在尝试使用按钮切换按钮的颜色。由于某种原因,下面的代码不起作用......

**//Header (.h)**
    @property UIColor *imageColor1;
    @property UIColor *imageColor2;    
    @property UIButton *button1;
    @property UIButton *button2;    
    @property CGRect viewBounds;
    -(IBAction)changeColor:(id)sender;    
    -(IBAction)createButton;

**//Implementation (.m)**
    @synthesize imageColor1;
    @synthesize imageColor2;
    @synthesize button1;
    @synthesize button2;
    @synthesize viewBounds;

    -(IBAction)createButton{
        self.viewBounds = self.view.bounds;

        self.button1 = [UIButton buttonWithType:UIButtonTypeCustom];
        self.button1.frame = CGRectMake(CGRectGetMidX(self.viewBounds)-30, CGRectGetMidY(viewBounds)-15, 60, 30); 
        self.button1.backgroundColor = self.imageColor1;
        [self.view addSubview:button1];

        self.button2 = [UIButton buttonWithType:UIButtonTypeCustom];
        self.button2.frame = CGRectMake(CGRectGetMidX(self.viewBounds)-15, CGRectGetMidY(viewBounds)-30, 30, 60); 
        self.button2.backgroundColor = self.imageColor2;          
        [self.view addSubview:button2];

    }

    -(IBAction)changeColor:(id)sender{

       int changeCount = 0;
       int changeCount1 = 1;
       NSArray *colors = [[NSArray alloc] initWithObjects:[UIColor redColor],[UIColor blueColor],[UIColor yellowColor],[UIColor                  magentaColor],[UIColor greenColor],[UIColor orangeColor],[UIColor purpleColor], nil];
       if(changeCount < 7){
          imageColor1 = [colors objectAtIndex:changeCount];
       }
       else{
          changeCount = changeCount - 5;
          imageColor1 = [colors objectAtIndex:changeCount];
       }
       if(changeCount1 < 7){
          imageColor2 = [colors objectAtIndex:changeCount1];
       }
       else{
          changeCount1 = changeCount1 - 5;
          imageColor2 = [colors objectAtIndex:changeCount1];
       }
       changeCount++;
       changeCount1++;
    }

基本上,每当用户点击“更改颜色”按钮时,变量changeCountchangeCount1会增加其计数,self.imageColor1self.imageColor2中的值会发生变化到数组colors中的后续值。由于某种原因,此代码不起作用,颜色不会更改。 createButton方法有效,因为无论何时按下它,都会出现一个新按钮,但如果我创建一个按钮,然后按更改颜色按钮然后再创建另一个按钮,则新按钮的颜色仍然相同。所以基本上我需要知道我的代码有什么问题。提前谢谢。

1 个答案:

答案 0 :(得分:2)

那是因为你每次都重置changeCount和changeCount1变量。请注意,您重新创建它们并在开头将它们设置为0和1?所以他们当然永远不会改变。您正在创建它们,就像它们是静态变量一样,但它们不是。它们是局部变量。 NSArray可以是静态的,但计数变量最好作为成员变量(即在您的界面中定义)。