从Plist中获取颜色。iOS

3

我想从我的plist字典中检索出一个UIColor,但是在这方面遇到了一些麻烦。

我将我的UIColor添加到我的plist字典中,然后在字符串中添加。(请参见附图)

我在我的plist中像这样保存它们:

[UIColor colorWithRed:57/255.0 green:131/255.0 blue:50/255.0 alpha:1]

然后我有一个文件,里面保存了我所有的颜色,例如:

+ (instancetype)titleBarColor
{
return [UIColor colorWithRed:57/255.0 green:131/255.0 blue:50/255.0 alpha:1];
}

但我想做类似于以下内容的事情:
+ (instancetype)titleBarColor
{

NSBundle* settings = [NSBundle mainBundle];
NSMutableDictionary *testing = [settings objectForInfoDictionaryKey: @"appColours"];
UIColor *test = [testing objectForKey:@"titleBarColor"];
NSLog(@"Test Colour %@", test);
return test;
}

但显然会因为颜色被字符串捕捉而崩溃。

1
将它们存储为十六进制字符串值。 - CW0007007
UIColor 实例不能直接存储到属性列表中。只能存储 NSNumberNSStringNSDataNSDate 实例以及(可能嵌套的)这些实例的字典/数组。 - Nicolas Miari
2个回答

3
我将它们存储为十六进制值,然后使用以下方法检索:
+ (UIColor *)colorFromHexString:(NSString *)hexString andAlpha:(CGFloat)alpha {

    //If non valid string:
    if (!hexString)
        return nil;

    unsigned rgbValue = 0;
    NSScanner *scanner = [NSScanner scannerWithString:hexString];
    [scanner setScanLocation:1]; // bypass '#' character
    [scanner scanHexInt:&rgbValue];
    return [UIColor colorWithRed:((rgbValue & 0xFF0000) >> 16)/255.0 green:((rgbValue & 0xFF00) >> 8)/255.0 blue:(rgbValue & 0xFF)/255.0 alpha:alpha];
}

或者简单地将浮点值以逗号分隔保存,并解析它。有一些解决方案...


0
这是CW0007007回答的Swift 3 / iOS 10版本:
extension UIColor{
    static func colorFrom(hexString:String, alpha:CGFloat = 1.0)->UIColor{
        var rgbValue:UInt32 = 0
        let scanner = Scanner(string: hexString)
        scanner.scanLocation = 1 // bypass # character
        scanner.scanHexInt32(&rgbValue)
        let red = CGFloat((rgbValue & 0xFF0000) >> 16)/255.0
        let green = CGFloat((rgbValue & 0x00FF00) >> 8)/255.0
        let blue = CGFloat((rgbValue & 0x0000FF) >> 8)/255.0
        return UIColor(red: red, green: green, blue: blue, alpha: alpha)
    }
}

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