How to save a UISlider's Position (Or current value)?
I am having trouble trying to save a UISlider
position (or current value) after leaving its ViewController
. The UISlider
is in my apps settings ViewController
, and c开发者_如何转开发ontrols the music volume in the app. When I change the value and leave the settings ViewController
, the music uses the level the user chose. However, if you return to the settings ViewController
it goes back to the default value I had set in the interface builder.
I have already tried saving its value with NSUserDefaults
but didn't have any success. How should I go about implementing this type of code?
NSUserDefaults is an easy and effective way to save settings like that, but it only saves the value you give it. You'll still need to retrieve the value and use it to set the slider's value the next time you load that controller. It would help if you'd post the code that's giving you trouble, as well as a description of exactly what isn't working. Are you able to save the value in the sharedDefaults object? Are you able to retrieve it?
To save the value for a slider that controls temperature, for example, you'd do something like the following:
[[NSUserDefaults sharedDefaults] setFloat:temperatureSlider.value forKey:@"temperature"];
and to restore the slider, you'd say:
float temperature = [[NSUserDefaults sharedDefaults] floatForKey:@"temperature"];
temperatureSlider.value = temperature;
Of course, it's always nice to use constants for things like @"temperature". I'm just trying to keep it as simple as possible here.
精彩评论