IOS: How to change the background image of a button when clicked?

10,879

There's quite a lot wrong with this code. Rather than list everything I'll just show you what it should be!

happydaysViewController.h file:

@interface happydaysViewController : UIViewController

@property (nonatomic, strong) IBOutlet UILabel *label;    //in IB drag this to your label
@property (nonatomic, strong) IBOutlet UIButton *button;    //in IB drag this to your button

-(IBAction)buttonClicked:(UIButton *)sender;    //in IB drag you button to this action

@end

happydaysViewController.m file:

#import "happydaysViewController.h"

@implementation happydaysViewController

@synthesize label;
@synthesize button;

-(IBAction)buttonClicked:(UIButton *)sender
{
    label.text = @"pop tart";
    UIImage *image = [UIImage imageNamed:@"Costa Rican Frog.jpg"];
    [sender setImage:image forState:UIControlStateNormal];
}

@end

So things to fix (in no particular order):

  1. You can't set an image value with a string, you need to create a UIImage object and load the image file into it. Fortunately [UIImage imageNamed:...] makes that very easy.

  2. Buttons can have multiple images for different states (highlighted, selected, disabled, etc) so you have to specify the sate when you set the image.

  3. The error you are getting indicates that you haven't actually got a property called button, which may be because you never added it to your class, or it may be because you've named your IBAction method "button" and this is conflicting with the getter method for the property called button, which would also be called "button". In my code I'm passing the button as a parameter to the click method (you'll need to re-bind the button in IB if you change its name), which a) provides another way to get the button and b) changes the name of the method so it won't conflict if you do want to have a property called button on your view controller.

Share:
10,879
tonyrocks
Author by

tonyrocks

Reggie Jackson's co-host.

Updated on June 05, 2022

Comments

  • tonyrocks
    tonyrocks almost 2 years

    I have a button that when it is clicked, it changes the text of a label. Here is a snippet of my code from my controller module (happydaysViewController.m):

    #import "happydaysViewController.h"
    
    @implementation happydaysViewController
    
    -(IBAction)button {
    
        label.text = @"pop tart";
        button.image = @"Costa Rican Frog.jpg";
    }
    

    So, the label text changes from blank to pop tart, however the background image of the button does not change from blank to Costa Rican Frog.jpg. In fact, I get the following error:

    'button' undeclared

    Am I approaching this the wrong way?