Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIButton selected state change image

I know this should be very simple but since I really have looked around here and on google without getting my code to work I will ask. Yes, I have checked related questions and they does not work...

I simply want to change the image of the button when it is pressed.

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 have also tried to do it in the attributes inspector but neither way worked!

enter image description here

Please note that I am not looking for how to do highlighted state but selected.

like image 849
M. El-Set Avatar asked Jul 15 '15 13:07

M. El-Set


2 Answers

You need to set the image for each state from your interface builder and you don't need to add a code if you want :

Select the State Config to Default and then choose an image

Default state

Select the State Config to Selected and then choose an image

Selected

And now to test each state of the button:

button states

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

like image 132
Alaeddine Avatar answered Nov 01 '22 03:11

Alaeddine


I believe what you need to do is set the button's state to selected when the button is tapped. Probably something like this:

-(IBAction)buttonTapped:(id)sender {
    if(self.myButton.selected)
        [self.mybytton setSelected:NO];
    else
        [self.mybutton setSelected:YES];
}
like image 13
dudeman Avatar answered Nov 01 '22 04:11

dudeman