0
votes

I have an application where I initially set a UIButton's background image, and then need to change it to something else later. I do realize I could just remove the original button and allocate a new button with the new image, but I'd prefer to be more efficient and reuse the object that I've already allocated. Is is possible to do this? I noticed that the currentBackgroundImage property is readonly, so when I try stuff like:

        [thumbnailButton setBackgroundImage:nil forState:UIControlStateNormal];
        [thumbnailButton setBackgroundImage:[UIImage imageWithCGImage:[[photos objectAtIndex: currentPhotoIndex] thumbnail]] forState:UIControlStateNormal];

or just:

        [thumbnailButton setBackgroundImage:[UIImage imageWithCGImage:[[photos objectAtIndex: currentPhotoIndex] thumbnail]] forState:UIControlStateNormal];

I get the following:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UITableViewCellContentView setBackgroundImage:forState:]: unrecognized selector sent to instance 0x16c570'

Is it possible to accomplish using UIButton or do I just need delete the original button and create a new one?

3
Are you saying that the setBackgroundImage:forState: is not working?picciano
@picciano - Yes, I updated with error message.Ser Pounce
Please, say what is a edit and what is the original questionGaroal

3 Answers

4
votes

You have a memory management problem here.

* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UITableViewCellContentView setBackgroundImage:forState:]: unrecognized selector sent to instance 0x16c570'

This means that your thumbnailButton is not pointing at a UIButton, but rather a UITableViewCellContentView. This could happen by improper assignment or if the UIButton is deallocated (in this case you have have a dangling pointer). Run the analyzer and double check your use of the button.

UIButton buttonWithType returns an autoreleased instance, so you need to retain it.

2
votes

In the UIButton class reference you can read that the method setBackground:forState: can be used.

1
votes

This should work fine. I think the Button has to be a Custom Button.

UIButton *sampleButton = [UIButton buttonWithType:UIButtonTypeCustom];