简体   繁体   中英

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.

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

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];
}

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.

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM