Save UIButton state and load with NSUserDefaults

我的梦境 提交于 2019-12-25 03:55:31

问题


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


回答1:


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]];
}



回答2:


To check out the button state, check this post: Xcode: Check if UIButton is hidden, using NSUserDefaults

Regarding the Alpha, try to ask for the return value of: self.button.alpha;

you can update the state (value) of the button and the Alpha button in an SQLite database. In the viewDidLoad method, call back the values from the database and apply them immediately. On how to do this, check out some more info on the web and you'll get there because the internet is filled with tutorials on the topic. Well, that's what I would do, SQLite is really useful actually; but perhaps there are other ways as well.



来源:https://stackoverflow.com/questions/7324689/save-uibutton-state-and-load-with-nsuserdefaults

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!