如何从Plist文件中加载一个UIColor

9

关于在Plist中保存UIColor:

我尝试了不同的方法,但无法实现。我想要将颜色值保存并检索到plist文件中。

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

还有其他方法可以实现吗?

4个回答

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);
    }
}

3

如果需要快速解决问题(但可能不太美观):

  • 将颜色属性作为数字类型添加到plist中
  • 以RGB十六进制形式输入颜色,例如: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);

在输入十六进制颜色后,plist编辑器会将其显示为十进制数,这不太友好。作为开发者,你通常会从设计文档中复制粘贴颜色,所以读取颜色值的需求并不那么大。


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相同的格式。实际上,这是[eppz!kit在GitHub上的一个更大规模的plist对象表现器][1]的一部分。
[1]: https://github.com/eppz/eppz-kit

请注意,红色、绿色和蓝色的取值范围是0.0-1.0,而不是0-255,因此需要将它们除以255才能得到正确的值。这个问题曾经让我困扰了一段时间。 - amergin
这是用于存储在 plist 中的,您可能想要在 plist 中“设计”颜色。有关 RGB 转换助手,请参见 https://dev59.com/tWYs5IYBdhLWcg3wAfEi#21297254 和 https://dev59.com/3HRC5IYBdhLWcg3wAcXU#21296829。 - Geri Borbás

-1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接