1

我看了又看,寻找这个,当我终于找到一些东西时,它不起作用。我正在尝试保存和加载用户选择的文本颜色。这是我的保存按钮:

-(IBAction)save123456 {
    NSData *colorData = [NSKeyedArchiver archivedDataWithRootObject:textview];
    [[NSUserDefaults standardUserDefaults] setObject:colorData forKey:@"myColor"];
}

这是我的负担:

-(IBAction)load123456 {
    NSData  *colorData = [[NSUserDefaults standardUserDefaults] objectForKey:@"myColor"];
    UIColor *color = [NSKeyedUnarchiver unarchiveObjectWithData:colorData];
}

如果有帮助,我的文本视图是 textview。此外,我正在通过 tuchupinside 链接所有内容,因此请告诉我是否应该更改任何内容。

此外,如果有人知道如何保存用户选择的文本字体也会有所帮助。非常感谢!!

4

1 回答 1

0

好吧,你可以保存颜色的 RGB。和字体的字体名称。因此,当您保存时,请为 font: 和颜色的 RGB 存储这些font.fontNamefont.pointSize在这里,您可以看到如何获取UIColor对象的 RGB。这些都是 NSString 和 float 值,因此您在保存它们时应该没有任何问题。

- (NSString *) pahtForFile:(NSString*) filename
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:filename];
}


- (void) save
{
//get RGB and fontName , fontSize like I explained above

NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
[dictionary setObject:fontName forKey:@"fontName"];
[dictionary setObject:[NSNumber numberWithFloat:fontSize]   forKey:@"fontSize"];
[dictionary setObject:[NSNumber numberWithFloat:red]    forKey:@"red"];
[dictionary setObject:[NSNumber numberWithFloat:green]  forKey:@"green"];
[dictionary setObject:[NSNumber numberWithFloat:blue]   forKey:@"blue"];

NSString *filepath = [self pathForFile:@"save.plist"];
[dictionary writeToFile:filepath atomically:TRUE];
}

- (void) load 
{
float red,green,blue,fontSize;
NSString *fontName;

NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfFile:[self pahtForFile:@"save.plist"]];
red = [[dictionary objectForKey:@"red"] floatValue];
green = [[dictionary objectForKey:@"green"] floatValue];
blue = [[dictionary objectForKey:@"blue"] floatValue];

fontSize = [[dictionary objectForKey:@"fontSize"] floatValue];
fontName = [dictionary objectForKey:@"fontName"];

//now rebuild color and font like this:
UIColor *color = [UIColor colorWithRed:red green:green blue:blue alpha:1];
UIFont *font = [UIFont fontWithName:fontName size:fontSize];
}

希望这可以帮助。顺便说一句:如果您发现答案有用,请将其标记为正确。

干杯,

乔治

于 2012-07-05T07:02:20.423 回答