我一直在寻找这个问题一段时间没有成功。我的问题是:是否有一种简单的方法可以在我的应用程序目录中的.plist文件中存储和获取[UIColor blackColor]
或[UIColor colorWithRed:0.38 green:0.757 blue:1 alpha:1];
等UIColors?
答案 0 :(得分:7)
根据this discussion,您有两种选择:
NSData选项
NSData *theData = [NSKeyedArchiver archivedDataWithRootObject:[UIColor greenColor]];
NSString选项
NSString *color = @"greenColor";
[UIColor performSelector:NSSelectorFromString(color)]
在此处阅读更多内容:http://www.iphonedevsdk.com/forum/iphone-sdk-development/27335-setting-uicolor-plist.html
答案 1 :(得分:4)
如果你想保持人类的可读性, 我为此做了一个类别:
@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对象代表的一部分。
答案 2 :(得分:1)
Objective-c中最好的可读方法是将其保存为十六进制字符串,例如:“#1A93A8”,然后通过extern方法获取它;
.h文件中的
:extern UIColor *colorFromHEX(NSString *hex);
extern NSString *HEXFromColor(UIColor *color);
.m文件中的
UIColor *colorFromHEX(NSString *hex){
NSString *stringColor = hex;
int red, green, blue;
sscanf([stringColor UTF8String], "#%02X%02X%02X", &red, &green, &blue);
UIColor *color = [UIColor colorWithRed:red/255.0 green:green/255.0 blue:blue/255.0 alpha:1];
return color;
}
NSString *HEXFromColor(UIColor *color){
const CGFloat *components = CGColorGetComponents(color.CGColor);
size_t count = CGColorGetNumberOfComponents(color.CGColor);
if(count == 2){
return [NSString stringWithFormat:@"#%02lX%02lX%02lX",
lroundf(components[0] * 255.0),
lroundf(components[0] * 255.0),
lroundf(components[0] * 255.0)];
}else{
return [NSString stringWithFormat:@"#%02lX%02lX%02lX",
lroundf(components[0] * 255.0),
lroundf(components[1] * 255.0),
lroundf(components[2] * 255.0)];
}
}
在任何地方
NSDictionary *Config = [[NSDictionary alloc] initWithContentsOfFile:[NSBundle.mainBundle pathForResource:@"Config" ofType:@"plist"]];
UIColor *color = colorFromHEX( Config[@"color"] );
NSString *strColor = HEXFromColor( UIColor.blackColor );