I have a floor in my logic, I'm struggling to find it. I have three buttons on my app which have two states, on and off. I have different images for each state, the buttons and image swapping is working well. My problem is on load, no matter what state the buttons are saved to, my buttons load to a selected state.
In my viewDidLoad I grab the states from memory:
NSString *_greyButtonSavedState = [[NSUserDefaults standardUserDefaults] stringForKey:@"greyButton"];
I then immediately check the state and apply the correct image (this isn't working):
if ([_greyButtonSavedState isEqualToString:@"ON"]) { [_greyButton setSelected:YES]; } else { [_greyButton setSelected:NO]; }
Each time the button is pressed I run the following:
- (IBAction) _greyButtonPress:(id)sender {
if ([sender isSelected]) {
NSLog(@"Grey map not created");
[sender setImage:_unselectedGrey forState:UIControlStateNormal];
[sender setSelected:NO];
//save state to memory
[[NSUserDefaults standardUserDefaults] setValue:@"OFF" forKey:@"greyButton"];
}else {
NSLog(@"Grey map created");
[sender setImage:_selectedGrey forState:UIControlStateSelected];
[sender setSelected:YES];
//save state to memory
[[NSUserDefaults standardUserDefaults] setValue:@"ON" forKey:@"greyButton"];
}
}
The logs show that on viewDidLoad the image being used is 'selected' but the button is in an 'unselected' mode. I have tried with and without:
[[NSUserDefaults standardUserDefaults] synchronize];
being called each time the button is pressed, no difference.
Any help would be great, thanks.
Well, I notice in one case you use UIControlStateNormal, but the other you use UIControlStateSelected. I think that is the source of your problem.
You are saying "If it is selected, set the image to unselected" and "If it is not selected, set the selected image to selected.