2011-08-02 59 views
2

是否有可能以某种方式保存Plist文件中的颜色代码?iPhone的UIColor Plist文件

我必须用字符串表示它们吗?然后我可以从他们创建颜色?

我看到了类似的主题在这里关于这个,但一直无人接听尚未

可以做些什么?

回答

3

UIColorsee here)符合NSCoding协议(see here),这意味着你可以把它们写出来的plist中,如果你做到这一点使用NSCoding

有一个伟大的教程here有关保存和使用NSCoding

+0

tnx你可以看看http://stackoverflow.com/questions/6911956/iphone-managing-reusable-uiimages-and-uiviews – Spring

+1

我也回答了这个问题:) –

4

我可以给你一个建议恢复应用数据。您可以将RGB值存储在数组中,并将该数组存储在plist的每一行中,而不是存储颜色名称。

键 - 红色 类型 - 阵列 值 - 1.0,0.0,0.0

检索每个键阵列。

NSArray *colorsArray = [dictionaryFromPlist objectForKey:@"Red"]; 
UIColor *mycolor = [UIColor colorWithRed:[[colorsArray objectAtIndex:0] floatValue] 
            green:[[colorsArray objectAtIndex:1] floatValue] 
            blue:[[colorsArray objectAtIndex:2] floatValue] 
            alpha:1.0]; 

只是我的想法..

+0

tnx如果它是与alpha通道? – Spring

+1

将它存储在plist数组中的下一个索引值 - 1.0,0.0,0.0,1.0 – iPrabu

2

您可以使用的NSKeyedArchiver从NSCoder

NSData *data = [NSKeyedArchiver archivedDataWithRootObject:[UIColor purpleColor]]; 
[[NSUserDefaults standardUserDefaults] registerDefaults:@{@"color": data}]; 

继承,使色彩回来了,你会用NSKeyedUnarchiver

NSDictionary *dict = [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]; 
NSLog(@"%@", [NSKeyedUnarchiver unarchiveObjectWithData: dict[@"color"]]); 
1

为了保持可读性,我做了这个类别:

@implementation UIColor (EPPZRepresenter) 


NSString *NSStringFromUIColor(UIColor *color) 
{ 
    const CGFloat *components = CGColorGetComponents(color.CGColor); 
    return [NSString stringWithFormat:@"[%f, %f, %f, %f]", 
      components[0], 
      components[1], 
      components[2], 
      components[3]]; 
} 

UIColor *UIColorFromNSString(NSString *string) 
{ 
    NSString *componentsString = [[string stringByReplacingOccurrencesOfString:@"[" withString:@""] stringByReplacingOccurrencesOfString:@"]" withString:@""]; 
    NSArray *components = [componentsString componentsSeparatedByString:@", "]; 
    return [UIColor colorWithRed:[(NSString*)components[0] floatValue] 
          green:[(NSString*)components[1] floatValue] 
          blue:[(NSString*)components[2] floatValue] 
          alpha:[(NSString*)components[3] floatValue]]; 
} 


@end 

所使用的NSStringFromCGAffineTransform相同的格式。这实际上是在[GitHub]的[eppz!kit] [1]中更大规模的plist对象代表的一部分。

+0

http://stackoverflow.com/a/21701710/3634990是一个更好的答案 – jungledev