Creating a UIColor from a Hex String in iOS Development

Creating a UIColor from a Hex String in iOS Development

22 May 2024 Stephan Petzl Leave a comment Tech-Help

When developing iOS applications, there are times you might need to convert a hexadecimal color code to a UIColor object. This guide will walk you through various methods to achieve this, ensuring you have a robust solution for your projects.

Using Macros for UIColor Conversion

A straightforward approach to convert a hex string to UIColor is by using a macro. This method is efficient and can be easily included in your header file for global usage:

#define UIColorFromRGB(rgbValue) \
    [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 \
                    green:((float)((rgbValue & 0x00FF00) >>  8))/255.0 \
                     blue:((float)(rgbValue & 0x0000FF))/255.0 \
                    alpha:1.0]
    

Usage example:

label.textColor = UIColorFromRGB(0xBC1128);

Objective-C Method for Hex String Conversion

Another common method involves creating a utility function that converts a hex string to UIColor:

+ (UIColor *)colorFromHexString:(NSString *)hexString {
        unsigned rgbValue = 0;
        NSScanner *scanner = [NSScanner scannerWithString:hexString];
        [scanner setScanLocation:1]; // bypass '#' character
        [scanner scanHexInt:&rgbValue];
        return [UIColor colorWithRed:((rgbValue & 0xFF0000) >> 16)/255.0
                               green:((rgbValue & 0xFF00) >> 8)/255.0
                                blue:(rgbValue & 0xFF)/255.0
                               alpha:1.0];
    }
    

Swift Implementation for UIColor Conversion

If you are developing with Swift, here is a concise way to achieve the same result:

extension UIColor {
        convenience init?(hexString: String) {
            let hexString: String = hexString.trimmingCharacters(in: .whitespacesAndNewlines)
            let scanner = Scanner(string: hexString)
            if hexString.hasPrefix("#") {
                scanner.scanLocation = 1
            }
            var color: UInt32 = 0
            scanner.scanHexInt32(&color)
            let mask = 0x000000FF
            let r = CGFloat(Float((color >> 16) & mask) / 255.0)
            let g = CGFloat(Float((color >> 8) & mask) / 255.0)
            let b = CGFloat(Float(color & mask) / 255.0)
            self.init(red: r, green: g, blue: b, alpha: 1)
        }
    }
    

Usage example:

let color = UIColor(hexString: "#FF5733")

Handling Different Hex Formats

To make your solution more robust, consider supporting various hex string formats like `#RGB`, `#ARGB`, `#RRGGBB`, and `#AARRGGBB`:

+ (UIColor *)colorWithHexString:(NSString *)hexString {
        NSString *cleanString = [hexString stringByReplacingOccurrencesOfString:@"#" withString:@""].uppercaseString;
        CGFloat alpha, red, blue, green;
        switch ([cleanString length]) {
            case 3:
                alpha = 1.0f;
                red   = [self colorComponentFrom:cleanString start:0 length:1];
                green = [self colorComponentFrom:cleanString start:1 length:1];
                blue  = [self colorComponentFrom:cleanString start:2 length:1];
                break;
            case 4:
                alpha = [self colorComponentFrom:cleanString start:0 length:1];
                red   = [self colorComponentFrom:cleanString start:1 length:1];
                green = [self colorComponentFrom:cleanString start:2 length:1];
                blue  = [self colorComponentFrom:cleanString start:3 length:1];
                break;
            case 6:
                alpha = 1.0f;
                red   = [self colorComponentFrom:cleanString start:0 length:2];
                green = [self colorComponentFrom:cleanString start:2 length:2];
                blue  = [self colorComponentFrom:cleanString start:4 length:2];
                break;
            case 8:
                alpha = [self colorComponentFrom:cleanString start:0 length:2];
                red   = [self colorComponentFrom:cleanString start:2 length:2];
                green = [self colorComponentFrom:cleanString start:4 length:2];
                blue  = [self colorComponentFrom:cleanString start:6 length:2];
                break;
            default:
                [NSException raise:@"Invalid color value" format:@"Color value %@ is invalid. It should be a hex value of the form #RGB, #ARGB, #RRGGBB, or #AARRGGBB", hexString];
                break;
        }
        return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
    }

    + (CGFloat)colorComponentFrom:(NSString *)string start:(NSUInteger)start length:(NSUInteger)length {
        NSString *substring = [string substringWithRange:NSMakeRange(start, length)];
        NSString *fullHex = length == 2 ? substring : [NSString stringWithFormat:@"%@%@", substring, substring];
        unsigned hexComponent;
        [[NSScanner scannerWithString:fullHex] scanHexInt:&hexComponent];
        return hexComponent / 255.0;
    }
    

Conclusion

Using these methods, you can easily convert hexadecimal color codes to UIColor objects in your iOS applications, enhancing the flexibility and customization of your UI components. For more advanced techniques and configurations, you can explore our documentation on Advanced Configuration.

Automate Your Testing with Repeato

While implementing these color conversions, ensure your app maintains high quality by utilizing automated tests. Repeato is a no-code test automation tool for iOS and Android that allows you to create, run, and maintain automated tests efficiently. With Repeato, mobile developers can focus on creating great products without the overhead of maintaining tests, and non-technical colleagues can also contribute to the testing process. Learn more about Repeato and how it can streamline your testing workflow on our blog.

Like this article? there’s more where that came from!