我正在尝试从字典中的plist中检索UIColor但是在执行此操作时遇到了一些麻烦。
我将我的UIColors在我的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;
}
但显然是由于字符串拾取颜色而导致崩溃。
答案 0 :(得分: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];
}
或者只是保存用逗号分隔的浮点值并将其解析出来。有一些解决方案......
答案 1 :(得分: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)
}
}