Reputation: 83
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.
Upvotes: 7
Views: 13694
Reputation: 14063
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]];
}
Upvotes: 14
Reputation: 1708
I think you have two options..
First:
You can put the [nine setBackgroundColor:[UIColor redColor]]; inside "clickDigit" (and like dasdom said rename to sender and change to (UIButton*)sender)..
Change
[nine addTarget:self action:@selector(changeButtonBackGroundColor:) forControlEvents:UIControlEventTouchUpInside];
to
[nine addTarget:self action:@selector(changeButtonBackGroundColor:) forControlEvents:UIControlEventTouchUpOutside];
and the method "changeButtonBackGroundColor"
[sender setBackgroundColor:[UIColor cyanColor]];
Second
create universal UIControlEvents
[nine addTarget:self action:@selector(changeButtonBackGroundColor:) forControlEvents:UIControlEventAllEvents];
-(void)changeButtonBackGroundColor:(UIButton*) sender{
if ([sender.backgroundColor isEqual:[UIColor redColor]]){
[sender setBackgroundColor:[UIColor cyanColor]];
}else{
[sender setBackgroundColor:[UIColor redColor]];
}}
I didn't try this code
Upvotes: 3