UIButton Selected Status Change Image

I know this should be very simple, but since I really searched here and on Google without making my code work, I will ask. Yes, I checked related questions and they do not work ...

I just want to change the button image when clicked.

This is my header file:

#import <UIKit/UIKit.h> @interface ViewController : UIViewController @property (strong, nonatomic) IBOutlet UIButton *myButton; @end 

And my implementation file:

 #import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [self.myButton setImage:[UIImage imageNamed:@"normal.png"] forState:UIControlStateNormal]; [self.myButton setImage:[UIImage imageNamed:@"selected.png"] forState:UIControlStateSelected]; } @end 

The button is built and connected in Main.storyBoard, and I also tried to do this in the attribute inspector, but none of them work!

enter image description here

Note that I am not looking for how to make the selected state, but the selected one.

+5
source share
5 answers

I believe that you need to set the button state selected when the button is pressed. Maybe something like this:

 -(IBAction)buttonTapped:(id)sender { if(self.myButton.selected) [self.mybytton setSelected:NO]; else [self.mybutton setSelected:YES]; } 
+7
source

You need to set an image for each state from the interface builder, and you do not need to add code if you want:

Select State Config - Default , and then select an image

Default state

Select State Config - Selected , and then select an image.

Selecteded

And now to check each button state:

button states

You can do the same for the background image, just select the "Background" option

+6
source

Do you have a method when the button is pressed? If yes, put the following lines here:

 [self.myButton setSelected:YES]; [self.myButton setImage:[UIImage imageNamed:@"selected.png"] forState:UIControlStateSelected]; 
+1
source

Why not try setting the default background image to "normal.png";

 [self.mybutton setBackgroundImage:[UIImage imageNamed:@"normal.png"]]; 

And switch to "selected.png" when the button is executed.

 [self.mybutton setBackgroundImage:[UIImage imageNamed:@"selected.png"]]; 
0
source

Change any image that you need in the IB constructor in the Status Configuration, and add an action to this button and add this line of code, as indicated in @Aladin.

  @IBAction func btnPressed (_ sender: UIButton) { // If you want to change it for selected state when tapped. sender.isSelected = !sender.isSelected } 
0
source

All Articles