Blios
Blios

Reputation: 729

change the background image of button in objective-c?

I've a UIButton on cell of UITableView in my VC like this

arrowBtnUp = [UIButton buttonWithType:UIButtonTypeCustom];
arrowBtnUp.frame = CGRectMake(50,(65-19)/2,31, 31);
[arrowBtnUp setBackgroundImage:[UIImage imageNamed:@"arrow_up.png"] forState:UIControlStateNormal];
[arrowBtnUp addTarget:self action:@selector(slideAction) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:arrowBtnUp];

and this my slideAction

-(void) slideAction
{
    [arrowBtnUp setBackgroundImage:[UIImage imageNamed:@"arrow_down.png"] forState:UIControlStateNormal];
    // also tried  with UIControlStateSelected/Highlighted
}

But it didn't work.I found this link but didn't help. Any suggestion or sample would be appreciated.

Upvotes: 0

Views: 2633

Answers (5)

tejas
tejas

Reputation: 11

If you're trying to change the button image after a touch, you should use the UIButton's control states. You can assign a background image for each "state" and let UIButton determine which to show.

Upvotes: 1

Midhun MP
Midhun MP

Reputation: 107121

The issue is you are reusing the arrowBtnUp instance of UIButton. Hence in the slideAction method you won't get the pressed buttons reference.

For getting the reference in the slideAction method you need to pass it as an argument.

So change the code like:

[arrowBtnUp addTarget:self action:@selector(slideAction:) forControlEvents:UIControlEventTouchUpInside];


-(void) slideAction:(UIButton *)myButton
{
   [myButton setBackgroundImage:[UIImage imageNamed:@"arrow_down.png"] forState:UIControlStateNormal];
}

Upvotes: 3

Edwin Iskandar
Edwin Iskandar

Reputation: 4119

If you're trying to change the button image after a touch, you should use the UIButton's control states. You can assign a background image for each "state" and let UIButton determine which to show.

[myButton setBackgroundImage:[UIImage imageNamed:@"arrow_up.png"] forState:UIControlStateNormal];
[myButton setBackgroundImage:[UIImage imageNamed:@"arrow_down.png"] forState:UIControlStateSelected];

There is no need to manually switch the background images in your slideAction: target method.

Upvotes: 0

Yunus Nedim Mehel
Yunus Nedim Mehel

Reputation: 12369

Background image is different than the icon on the button. Try this instead:

[_buttonConfirm setImage:[UIImage imageNamed:@"s.png"] forState:UIControlStateNormal];

Upvotes: 0

Pratyusha Terli
Pratyusha Terli

Reputation: 2343

Your code should work.Anyways change your code like this and try

-(void) slideAction:(id)sender
{
   [sender setBackgroundImage:[UIImage imageNamed:@"arrow_down.png"] forState:UIControlStateNormal];
}

and

[arrowBtnUp addTarget:self action:@selector(slideAction:) forControlEvents:UIControlEventTouchUpInside];

and ensure that you have arrow_down.png in your app bundle

Upvotes: 4

Related Questions