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];
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With