2011-04-06 58 views
0

我下面的教程hereHEX到UIColorfromRGB

這是相當簡單的,簡單的,只有幾步之遙。但在最後一步,我將HEX代碼作爲hexText.text存儲在UITextField中,但是如何將它放入UIColorFromRGB?

回答

2

here是一個避免宏的東西的解決方案。您可以將它添加到UIColor的類別並更好地使用它。

0

索林在這裏有正確的想法,我認爲。更多的可可類,並會導致更少的頭痛。要高層回答您的問題,您需要將您的字符串轉換爲十六進制數字,然後將結果值傳遞給宏。我認爲只要將字符串值傳遞給Sorin鏈接中列出的類別,就可以更好地服務。

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)]; 
}