5

I have a view and I created some 8 buttons programmatically in that. The title color of buttons is white color. I want to change color of button title to green color when it is clicked. And if i click any other button, the previously clicked button title color should become white and current button title color should become green.

How to do that?

Surendra
  • 201
  • 3
  • 6

3 Answers3

11

Initialize all your buttons like this

[mybutton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[mybutton setTitleColor:[UIColor greenColor] forState:UIControlStateSelected];
[mybutton addTarget:self action:@selector(onclick:) forControlEvents:UIControlEventTouchUpInside];

then change the selected state of you button when clicked

-(void)onclick:(id)sender{
UIButton *button = (UIButton *)sender;
button.selected = !button.selected;
}
Bordz
  • 2,810
  • 4
  • 23
  • 27
0

Create IBAction for all of the buttons, create a property @property (strong, nonatomic) UIButton *currentButton. In the action do the following:

-(IBAction)buttonClicked:(id)sender
{
    UIButton *buttonSender = (UIButton *)sender;

    [self.currentButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.currentButton = buttonSender;
    [self.currentButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
}
ivan_yorgov
  • 1,281
  • 1
  • 9
  • 7
0

Set control state of buttons :

[btnOk setTitleColor:[UIColor yellowColor] forState:UIControlStateSelected];
[btnOk setTitleColor:[UIColor yellowColor] forState:UIControlStateHighlighted];
[btnOk setTitleColor:[UIColor yellowColor] forState:UIControlStateNormal];
Divya Bhaloidiya
  • 5,018
  • 2
  • 25
  • 45