I have an NSButton set as a toggle (on/off) in my application. When I click the button it works fine, but when I try and programmatically set it using [toggleButton setEnabled:YES];
it has no effect.
code:
- (void)awakeFromNib {
defaults = [NSUserDefaults standardUserDefaults];
NSString *toggleValue = [[NSUserDefaults standardUserDefaults] objectForKey:@"toggleActive"];
if (toggleValue == nil) toggleValue = @"YES";
if ([toggleValue isEqualToString:@"YES"]) {
[defaults setObject:@"YES" forKey:@"toggleActive"];
isOn = YES;
[toggleButton setEnabled:YES];
}
if ([toggleValue isEqualToString:@"NO"]) {
[defaults setObject:@"NO" forKey:@"toggleActive"];
isOn = NO;
[toggleButton setEnabled:NO];
}
[[NSUserDefaults standardUserDefaults] synchronize];
}
- (IBAction)toggleButton:(id)sender {
if( isOn ) {
[self stopFunction: (NSButton *)sender];
isOn = NO;
[defaults setObject:@"NO" forKey:@"toggleActive"];
} else {
[self startFunction (NSButton *)sender];
isOn = YES;
[defaults setObject:@"YES" forKey:@"toggleActive"];
}
[[NSUserDefaults standardUserDefaults] synchronize];
}
*toggleActive
YES or NO get's stored in NSUserDefaults (which works fine); I'm wanting to remember the last button state when the user re-opens the application.
setEnabled: only changes the availability of the button to user interaction
The following will switch the button's image along with setting the button's state to on/off
[toggleButton setState:NSOnState];
[toggleButton setState:NSOffState];
If you would like to have the appropriate action to be taken along with the state change, you will have to call the appropriate functions as well
[toggleButton setState:NSOnState];
[self startFunction:toggleButton];
Alternatively, you can call
[toggleButton performClick:self];
However, this will cause a brief aqua blue shading of the button (like you are actually clicking on it) while it switches state. I prefer the former method on account of this.
All this is just made on some quick observations I made a little while ago, while trying to do the same thing (googling brought me to this thread). Hope this helps :)