I created a custom UIButton, and it has a field "selected" to identify that this button is selected or not. As default: it set its image as image1. When it is selected it changes to image2.
@interface MyButton: UIButton
@property (getter=isSelected, setter=setSelected:) BOOL selected;
@end
@implementation MyButton
@synthesize selected = _selected;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.selected = NO;
}
return self;
}
-(void) setSelected:(BOOL)selected
{
if (selected)
{
[self setImage:[UIImage imageNamed:@"image1"] forState:UIControlStateNormal];
}
else
{
[self setImage:[UIImage imageNamed:@"image2"] forState:UIControlStateNormal];
}
_selected = selected;
}
-(BOOL) isSelected
{
return _selected;
}
Now, from a UIViewController, I add this custom buttom to its view. And when the user click another button, I want my custom buttom should change its image (from image1 -> image2 and vice verse).
@interface SessionViewController (){
MyButton* btn;
}
@end
@implementation ViewController
- (void) viewDidLoad
{
[super viewDidLoad];
btn = [[MyButton alloc] initWithFrame: CGRectMake(0,0,100,100)];
}
- (IBAction) touchChangeStateButton
{
BOOL b = btn.isSelected;
btn.selected = !b;
}
@end
My question is why my custom buttom does not change its image??? Thanks.