How would I save a UIButton's properties and l

2019-03-06 16:46发布

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

2条回答
beautiful°
2楼-- · 2019-03-06 16:58

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"];
查看更多
干净又极端
3楼-- · 2019-03-06 16:58

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];
查看更多
登录 后发表回答