How can I convert RGB hex string into UIColor in objective-c?

后端 未结 4 2003
终归单人心
终归单人心 2020-11-30 10:17

I have color values coming from the url data is like this, \"#ff33cc\". How can I convert this value into UIColor? I am attempting with the following lines of code. I am not

4条回答
  •  一向
    一向 (楼主)
    2020-11-30 11:12

    I added a string replacement so it accepts a hex string with or without the #

    Possible full code:

    + (UIColor *)colorWithHexString:(NSString *)stringToConvert
    {
        NSString *noHashString = [stringToConvert stringByReplacingOccurrencesOfString:@"#" withString:@""]; // remove the #
        NSScanner *scanner = [NSScanner scannerWithString:noHashString];
        [scanner setCharactersToBeSkipped:[NSCharacterSet symbolCharacterSet]]; // remove + and $
    
        unsigned hex;
        if (![scanner scanHexInt:&hex]) return nil;
        int r = (hex >> 16) & 0xFF;
        int g = (hex >> 8) & 0xFF;
        int b = (hex) & 0xFF;
    
        return [UIColor colorWithRed:r / 255.0f green:g / 255.0f blue:b / 255.0f alpha:1.0f];
    }
    

提交回复
热议问题