Search code examples
xcodeuibuttonstatensuserdefaultsviewdidload

Save UIButton state and load with NSUserDefaults


I was wondering how to detect whether the button was hidden or not, and how much alpha was applied to it. Then, when viewDidLoad is called, these values can be applied to make the buttons the same state they were left in when the application closed.

How can I code this?

Thanks,

James


Solution

  • If, as your title suggests, you want to use NSUserDefaults, then you can set them like this:

    -(void)saveButtonState:(UIButton*)button {
        NSUserDefaults defaults = [NSUserDefaults standardUserDefaults];
        [defaults setBool:button.hidden forKey:@"isHidden"];
        [defaults setFloat:button.alpha forKey:@"alpha"];
    }
    
    -(void)restoreButtonState:(UIButton*)button {
        NSUserDefaults defaults = [NSUserDefaults standardUserDefaults];
        button.hidden = [defaults boolForKey:@"isHidden"];
        button.alpha = [defaults floatForKey:@"alpha"];
    }
    

    If you want to do this for multiple buttons, then you can use tags to differentiate between them in the defaults:

    -(void)saveButtonState:(UIButton*)button {
        NSUserDefaults defaults = [NSUserDefaults standardUserDefaults];
        [defaults setBool:button.hidden forKey:[NSString stringWithFormat:@"isHidden%d",button.tag]];
        [defaults setFloat:button.alpha forKey:[NSString stringWithFormat:@"alpha%d",button.tag]];
    }
    
    -(void)restoreButtonState:(UIButton*)button {
        NSUserDefaults defaults = [NSUserDefaults standardUserDefaults];
        button.hidden = [defaults boolForKey:[NSString stringWithFormat:@"isHidden%d",button.tag]];
        button.alpha = [defaults floatForKey:[NSString stringWithFormat:@"alpha%d",button.tag]];
    }