HEX to UIColorfromRGB

2019-08-20 02:36发布

I'm following a tutorial here

It's fairly straight forward and simple, only 2 steps. But on the last step, I have the HEX code in a UITextField as hexText.text, but how do i put that into UIColorFromRGB?

3条回答
Explosion°爆炸
2楼-- · 2019-08-20 03:17

here is a solution that avoids the macro stuff. You can add it to a category to UIColor and use it more nicely.

查看更多
甜甜的少女心
3楼-- · 2019-08-20 03:18

This will solve any case

+ (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)];
}
查看更多
Melony?
4楼-- · 2019-08-20 03:28

Sorin has the right idea here I think. Much more cocoa-like, and will result in fewer headaches. To answer your question at a high level, you'd need to convert your string to a hexadecimal number, and then pass that resulting value in to the macro. I think you'd be better served just passing the string value into the category listed in Sorin's link.

查看更多
登录 后发表回答