Hi,
I have been trying to figure out how to change the color of a UILabel and then save into the NSUserDefaults. I am using the Settings.bundle to change all of the settings. Here is the code I used...
Hi,
I have been trying to figure out how to change the color of a UILabel and then save into the NSUserDefaults. I am using the Settings.bundle to change all of the settings. Here is the code I used...
why would it change the colot if you said label.text all you are doing is saving the text. I dont get how you think that would save the color.
Yeah, I know it does not work. I have trying changing that to many different things, but none of them worked. So, I just wanted to show that code I had to work with!
Yeah, I know it does not work. I have trying changing that to many different things, but none of them worked. So, I just wanted to show that code I had to work with!
always look in the documentation before posting. It says theres a propert of UILabel called textColor.
To save a colour object, you first have to archive it into a data object. The "User Defaults Programming Topics for Cocoa" describes how to do this (although for an NSColor object, but since they behave in the same way...).
Warning: I haven't tried running this yet, and it's based on Apple's example code only altered to use an NSKeyedArchiver, so it may include errors, or may just simply blow up, but hopefully it should set you off in the right direction.
To save the colour:
Code:
// first get the colour you want to save
UIColor *theColour = label.textColor;
// archive it into a data object
NSData *data = [NSKeyedArchiver archivedDataWithRootObject: theColour];
// write the data into the user defaults
[[NSUserDefaults standardUserDefaults] setObject: data forKey: kColorKey];
And then to recover it:
Code:
// declare the colour var you'll be needing
UIColor *theColour;
// read the data back from the user defaults
NSData *data= [[NSUserDefaults standardUserDefaults] dataForKey: kColorKey];
// check whether you got anything
if(data == nil) {
// use this to set the colour the first time your app runs
theColour = [UIColor someColor];
} else {
// this recreates the colour you saved
theColour = (NSColor *)[NSKeyedUnarchiver unarchiveObjectWithData: data];
}
// and finally set the colour of your label
label.textColor = theColour;
__________________ SimCap - Simple iPhone and iPad Simulator screen capture