user3110353 user3110353 - 1 month ago 18
iOS Question

Retrieve Color from Plist. iOS

I am trying to Retrieve a UIColor from my plist in a dictionary but am having some trouble doing this.

I added my UIColors in my plist in a dictionary and then in strings. (See attached image)

i am saving them like so in my plist :

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


Then I have a file Where I save all my colours like:

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


but I would like to do something like :

+ (instancetype)titleBarColor
{

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


But obviously get a crash due to the color being picked up by a string.

Answer

I store them as hex values and then use the following to retrieve:

+ (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];
}

Or simply save the float values separated by a comma and parse it out. There's a few solutions ...