Reputation: 1017
I am just trying to set the button image to toggle to different images in my IBAction:
if ([sender isSelected]) {
//1
UIImage *unselectedImage = [[UIImage alloc]initWithContentsOfFile:@"icon_checkbox_up"];
[sender setImage:unselectedImage forState:UIControlStateSelected];
[sender setSelected:NO];
}
else {
//2
UIImage *unselectedImage = [[UIImage alloc]initWithContentsOfFile:@"icon_checkbox_down"];
[sender setImage:unselectedImage forState:UIControlStateNormal];
[sender setSelected:YES];
}
When I click on the button, the image changes accordingly (under the comment 2), after pressing the button again, the image just disappears. I'm not sure why that is. I've tried both UIControlStateSelected and UIControlStateNormal. Am I missing something?
Upvotes: 0
Views: 1198
Reputation: 1017
Changed the code to:
if ([sender isSelected]) {
[sender setSelected:NO];
}
else {
[sender setSelected:YES];
}
and set the images in XIB files for each UIControlState.
Upvotes: 0
Reputation: 347
If your file name isn't wrong, you could try this way. Hope it helps!!
[buttn addTarget:self action:@selector(Selected) forControlEvents:UIControlEventTouchDown];
[buttn addTarget:self action:@selector(Unselected) forControlEvents:UIControlEventTouchUpInside];
[buttn addTarget:self action:@selector(Unselected) forControlEvents:UIControlEventTouchUpOutside];
-(void)Selected
{
UIImage *unselectedImage = [[UIImage alloc]initWithContentsOfFile:@"icon_checkbox_up"];
[buttn setImage:unselectedImage forState:UIControlStateSelected];
[buttn setSelected:NO];
}
-(void)Unselected
{
UIImage *unselectedImage = [[UIImage alloc]initWithContentsOfFile:@"icon_checkbox_down"];
[buttn setImage:unselectedImage forState:UIControlStateNormal];
[buttn setSelected:YES];
}
Upvotes: 2