2010-12-15 42 views
8

关于将UIColor保存在Plist中: 我尝试过不同的方法,但是无法做到这一点,我想保存并检索plist文件中的颜色值。如何从Plist中加载UIColor

我无法使用nslog提取颜色的数据值并将其保存在plist中。

有没有其他方法可以做到这一点?

我发现这个问题

回答

7

我更喜欢用字符串来存储颜色。那这是否显示在下面的解析代码(从https://github.com/xslim/TKThemeManager/blob/master/TKThemeManager.m#L162切出)

+ (UIColor *)colorFromString:(NSString *)hexString {  
    NSScanner *scanner = [NSScanner scannerWithString:hexString]; 
    unsigned hex; 
    BOOL success = [scanner scanHexInt:&hex]; 

    if (!success) return nil; 
    if ([hexString length] <= 6) { 
     return UIColorFromRGB(hex); 
    } else { 
     unsigned color = (hex & 0xFFFFFF00) >> 8; 
     CGFloat alpha = 1.0 * (hex & 0xFF)/255.0; 
     return UIColorFromRGBA(color, alpha); 
    } 
} 
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

只是要注意的是,红色,绿色,蓝色值是0.0-1.0不0-255因此通过255除以他们得到正确的值 - 这让我出去了一会儿。 – amergin 2014-02-07 13:50:21

+0

这是为了存储在'plist'中,你可能想要“设计”'plist'中的颜色。对于RGB转换助手,请参阅http://stackoverflow.com/questions/13224206/how-do-i-create-an-rgb-color-with-uicolor/21297254#21297254和http://stackoverflow.com/questions/ 437113 /如何对获得-RGB值从 - 的UIColor/21296829#21296829。 – Geri 2014-02-07 15:42:30

3

对于一个快速的解决方案(但也许不是最漂亮的一个):

  • 添加颜色属性作为类型数到的plist
  • 输入颜色为RGB-hexdecimal,例如: 0xff00e3
  • 读出来,并与像下面

下面是一个代码示例的宏处理它:

// Add this code to some include, for reuse 
#define UIColorFromRGBA(rgbValue, alphaValue) ([UIColor colorWithRed:((CGFloat)((rgbValue & 0xFF0000) >> 16))/255.0 \ 
                   green:((CGFloat)((rgbValue & 0xFF00) >> 8))/255.0 \ 
                   blue:((CGFloat)(rgbValue & 0xFF))/255.0 \ 
                   alpha:alphaValue]) 

// This goes into your controller/view 
NSDictionary *myPropertiesDict = [NSDictionary dictionaryWithContentsOfFile:...]; 
UIColor *titleColor = UIColorFromRGBA([myPropertiesDict[@"titleColor"] integerValue], 1.0); 

进入颜色hexdecimal后,编辑的plist将展示它作为一个十进制数。不太好。作为开发人员,您通常会复制粘贴来自设计文档的颜色,因此读取颜色值的需求并不那么大。