Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIButton background image not changing

I want to change button background image as per the web service response. if in response I get unread messages to true then image will different and if there is no unread messages image will be different. I am getting the response very well but not able to change my button's background image.

This is the snippet I am using

if(unread>0){
    [badgeTitle setBackgroundImage:[UIImage imageNamed:@"unread.png"] forState:UIControlStateNormal];
}
else{
    [badgeTitle setBackgroundImage:[UIImage imageNamed:@"read.png"] forState:UIControlStateNormal];
}
like image 261
KDeogharkar Avatar asked Jan 13 '23 19:01

KDeogharkar


1 Answers

The solution can be very simple, if you look at it. Keep a global UIButton and not a local one. This helps, as when the web request returns back a response, the button needs to be present in-scope and not get removed from the memory.

So use,

self.myButton = [UIButton buttonWithType:UIButtonTypeCustom];

[self.myButton setBackgroundImage:[UIImage imageNamed:@"unread.png"] forState:UIControlStateNormal];

OR

[self.myButton setImage:[UIImage imageNamed:@"unread.png"] forState:UIControlStateNormal];

And, if you checking on the click of a button, then follow the steps :

-(IBAction)checkForMsgCount: (id)sender
{
  UIButton *buttonObj = (UIButton*)sender;

[buttonObj setBackgroundImage:[UIImage imageNamed:@"unread.png"] forState:UIControlStateNormal];
}

This changes the background image, for the button that is responding to the function.

like image 156
Hitesh Avatar answered Jan 21 '23 19:01

Hitesh