我正在关注教程here
这很简单,只有两个步骤。但是在最后一步,我在UITextField中将HEX代码作为hexText.text,但是我如何将它放入UIColorFromRGB?
答案 0 :(得分:2)
here是一种避免宏观内容的解决方案。您可以将它添加到UIColor的类别中并更好地使用它。
答案 1 :(得分:0)
答案 2 :(得分:0)
这将解决任何情况
+ (UIColor *) colorWithHexString: (NSString *) stringToConvert{
NSString *cString = [[stringToConvert stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
unsigned int r, g, b,alpha = 1;
NSRange range;
range.location = 0;
range.length = 2;
// 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 hasPrefix:@"#"]) cString = [cString substringFromIndex:1];
if ([cString length] == 8) {
[[NSScanner scannerWithString:[cString substringWithRange:range]] scanHexInt:&alpha];
cString = [cString substringFromIndex:2];
}
if ([cString length] != 6) return [UIColor blackColor];
// Separate into r, g, b substrings
NSString *rString = [cString substringWithRange:range];
range.location = 2;
NSString *gString = [cString substringWithRange:range];
range.location = 4;
NSString *bString = [cString substringWithRange:range];
// Scan values
[[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:((float) alpha / 255.0f)];
}