How would I save a UIButton's properties and load with a button? [duplicate]

て烟熏妆下的殇ゞ 提交于 2019-12-20 07:40:01

问题


Possible Duplicate:
How can I save and load the alpha values of a UIButton in an app?

I would like to save the state of the UIButton (e.g. its alpha value and whether it is hidden or not) and this would then load up when the user quits and reloads the app.

I've tried some bits of code with NSUserDefaults but with no luck.

Could somebody help with some sample code so that I can save and load the button's state?

Thanks,

James


回答1:


Related to Shaharyar's answer (i don't know how to comment):

in this case you need to use NSNumber.

[[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithFloat:SOME_FLOAT] forKey:KEY];

because float is not an object, but NSNumber is one.

EDITED:

1) To make sure your defaults are created after the application runs at first time: in your AppDelegate's initialize-method:

NSUserDefaults *defaults  = [NSUserDefaults standardUserDefaults];
NSDictionary *appDefaults = [NSDictionary dictionaryWithObjectsAndKeys:
                             [NSNumber numberWithFloat:SOME_FLOAT], @"YOUR_KEY", 
                             nil];
[defaults registerDefaults:appDefaults];

2) Updating defaults after:

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setFloat:FLOAT_VALUE forKey:@"YOUR_KEY"];
[prefs synchronize];

3) Read defaults:

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
float FLOAT_VALUE = [prefs floatForKey:@"YOUR_KEY"];



回答2:


Can you post some of the code?

NSUserDefaults is the place to store such information..

Assumption:

Did you make a call to [NSUserDefaults synchronize] after setting the values?


Code:

// Setting a value
[[NSUserDefaults standardUserDefaults] setValue:VALUE forKey:KEY];
[[NSUserDefaults standardUserDefaults] synchronize];

// Getting a value
NSString *var1 = [[NSUserDefaults standardUserDefaults] valueForKey:KEY];

In your case it would be:

// Setting a value
[[NSUserDefaults standardUserDefaults] setFloat:VALUE forKey:KEY];
[[NSUserDefaults standardUserDefaults] synchronize];


来源:https://stackoverflow.com/questions/7338218/how-would-i-save-a-uibuttons-properties-and-load-with-a-button

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