DixieFlatline
DixieFlatline

Reputation: 8035

Can't change background image of custom uiButton for selected state

With my code below, it seems that button is in normal state all the time (always green) eventhough i click on him.

UIButton *gumb = [UIButton buttonWithType:UIButtonTypeCustom];
     gumb.frame = CGRectMake(4, 40, 104, 37);
     gumb.tag=0;
    [gumb setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [gumb setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
    [gumb setBackgroundImage:[UIImage imageNamed:@"greenButton.png"] forState:UIControlStateNormal];
     [gumb setBackgroundImage:[UIImage imageNamed:@"whiteButton.png"] forState: UIControlStateSelected];

If i set image for normal state to whiteButton and for seleted to greenButton then the button is always white and never green.

Upvotes: 4

Views: 6756

Answers (4)

Bhoopi
Bhoopi

Reputation: 6593

Code for setting selected state image:

[_button setImage:[UIImage imageNamed:@"whiteButton.png"] forState: UIControlStateHighlighted];

Code for setting Normal state image:

[_button setImage:[UIImage imageNamed:@"whiteButton.png"] forState: UIControlStateNormal];

Upvotes: 0

BabyPanda
BabyPanda

Reputation: 1592

I not sure if Selected state is only used for tab-buttons, 'cause I've tried like DixieFlatline did and sometimes did make the button image change. But method of tt.Kilew is definitely worth trying. Just try: [gumb setBackgroundImage:[UIImage imageNamed:@"whiteButton.png"] forState: UIControlUIControlStateHighlighted]; and the button image will be changed on click.

Upvotes: 1

visakh7
visakh7

Reputation: 26390

Do you set the state of the button as selected in the button click action

- (IBAction)buttonClicked:(id)sender;
{
UIButton *button = (UIButton *)sender;
if(button.tag == 0)// in your case
{
button.selected = YES;
}
// Do something
}

Hope this helps

Upvotes: 0

Inder Kumar Rathore
Inder Kumar Rathore

Reputation: 39978

[gumb setBackgroundImage:[UIImage imageNamed:@"whiteButton.png"] forState: UIControlStateHighlighted] 

use this one instead of selected image

Upvotes: 4

Related Questions