Reputation: 11595
I am trying have a button that switches the color of a button. For some reason the code below isn't working...
**//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++;
}
Basically, whenever the user taps the "Change Color" button, the variables changeCount
and changeCount1
increase their count, and the values in self.imageColor1
and self.imageColor2
are changed to the subsequent values in the array colors
. For some reason, this code isn't working and the colors don't change. The createButton
method works because whenever I press it, a new button appears, but if I create a button and then press the change color button and then create another button, the color of the new button is still the same. So basically I need to know what's wrong with my code. Thanks in advance.
Upvotes: 1
Views: 556
Reputation: 33421
That's because you reset the changeCount and changeCount1 variables every time. Notice you recreate them and set them to 0 and 1 at the beginning? So of course they are never going to change. You are creating them as if they are static variables, but they are not. They are local variables. The NSArray could be static, but the count variables are better off as member variables (i.e. defined in your interface).
Upvotes: 2