Reputation: 763
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!
Please note that I am not looking for how to do highlighted state but selected.
Upvotes: 10
Views: 17778
Reputation: 1057
Change to whatever image you need in the IB builder in the State Config and add an action to that button and in that add this line of code as said by @Aladin.
@IBAction func btnPressed (_ sender: UIButton) {
// If you want to change it for selected state when tapped.
sender.isSelected = !sender.isSelected
}
Upvotes: 2
Reputation: 1136
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];
}
Upvotes: 13
Reputation: 1253
Do you have a method for when the button is clicked? If yes, put this below lines in there:
[self.myButton setSelected:YES];
[self.myButton setImage:[UIImage imageNamed:@"selected.png"] forState:UIControlStateSelected];
Upvotes: 1
Reputation: 6212
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
Select the State Config
to Selected
and then choose an image
And now to test each state of the button:
You can do the same for background image just select the parameter "Background"
Upvotes: 13
Reputation: 1954
Why not try to set background image default to "normal.png";
[self.mybutton setBackgroundImage:[UIImage imageNamed:@"normal.png"]];
And switch to "selected.png" when perform the button.
[self.mybutton setBackgroundImage:[UIImage imageNamed:@"selected.png"]];
Upvotes: 0