问题出在标题中,如何从Plist设置UILabel的UIColor?
我试过这个:
UIColor *colorLabel;
我在我的Plist中添加一个NSString行,并将redColor写为值,但不起作用......
我该如何处理?
谢谢你们。
答案 0 :(得分:0)
我认为你需要从字符串转换为UIColor。你用十六色(红色 - ff0000)将颜色放入你的plist中,然后使用类似下面的函数来获取UIColor。
+ (UIColor *) colorWithHexString: (NSString *) stringToConvert
{
NSString *cString = [[stringToConvert stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
// String should be 6 or 8 characters
if ([cString length] < 6) return [UIColor blackColor];
// strip 0X if it appears
if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];
if ([cString length] != 6) return [UIColor blackColor];
// Separate into r, g, b substrings
NSRange range;
range.location = 0;
range.length = 2;
NSString *rString = [cString substringWithRange:range];
range.location = 2;
NSString *gString = [cString substringWithRange:range];
range.location = 4;
NSString *bString = [cString substringWithRange:range];
// Scan values
unsigned int r, g, b;
[[NSScanner scannerWithString:rString] scanHexInt:&r];
[[NSScanner scannerWithString:gString] scanHexInt:&g];
[[NSScanner scannerWithString:bString] scanHexInt:&b];
return [UIColor colorWithRed:((float) r / 255.0f)
green:((float) g / 255.0f)
blue:((float) b / 255.0f)
alpha:1.0f];
}
答案 1 :(得分:0)
我个人会存储RGBA值而不是字符串然后你可以使用
+ (UIColor *)colorWithRed:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue alpha:(CGFloat)alpha
请勿执行以下操作
正如一个有趣的旁注,最不灵活的方式是使用像这样的UIColor
便利方法
[UIColor performSelector:NSSelectorFromString(@"redColor")]
答案 2 :(得分:0)
为了保持人类的可读性,我为此做了一个类别:
@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 at GitHub中更大规模的plist对象代表的一部分。