Karthikeya Karthikeya - 4 days ago 5
Objective-C Question

Changing UIButton background color

I am creating buttons programmatically. I want to change button background color while touching up inside again it has to set back to its usual color after lifting up our finger.....

nine = [UIButton buttonWithType:UIButtonTypeCustom];
[nine setFrame:CGRectMake(15, 105, 65, 40)];
[nine setTitle:@"9" forState:UIControlStateNormal];
[nine setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[nine setBackgroundColor:[UIColor cyanColor]];
[nine addTarget:self action:@selector(clickDigit:) forControlEvents:UIControlEventTouchUpInside];
[nine addTarget:self action:@selector(changeButtonBackGroundColor:) forControlEvents:UIControlEventTouchUpInside];

[self.view addSubview:nine];


// to change background color

-(void)changeButtonBackGroundColor:(id) sender
{
[nine setBackgroundColor:[UIColor redColor]];
}


Here changeBackgroundColor method was created to change color of that button . it changes color.

Answer

Don't know if this relates to your question but: this

[nine setBackgroundColor:[UIColor redColor]];

should be

[sender setBackgroundColor:[UIColor redColor]];

Edit: Change this

[nine addTarget:self action:@selector(changeButtonBackGroundColor:) forControlEvents:UIControlEventTouchUpInside];

to

[nine addTarget:self action:@selector(changeButtonBackGroundColor:) forControlEvents:UIControlEventTouchDown];
[nine addTarget:self action:@selector(resetButtonBackGroundColor:) forControlEvents:UIControlEventTouchUpInside];
[nine addTarget:self action:@selector(resetButtonBackGroundColor:) forControlEvents:UIControlEventTouchUpOutside];
[nine addTarget:self action:@selector(resetButtonBackGroundColor:) forControlEvents:UIControlEventTouchCancel];

and add the method:

- (void)resetButtonBackGroundColor: (UIButton*)sender {
    [sender setBackgroundColor:[UIColor cyanColor]];
}
Comments