Search code examples
iosobjective-ccocoa-touchclruicolor

NSColorList for iOS, or some way to share colors between IB and code


When developing my apps I usually create a category on UIColor and a custom color palette (CLR file) for Interface Builder for my specific colors. But this means I have to add new colors and update old colors in 2 places. I could create a bunch of IBOutlets, set colors in code, and not use the CLR file, but I hate creating a ton of IBOutlets.

I would like to include the CLR file in my bundle and then access the colors wherever I need in code. On OS X I believe I could achieve this with the NSColorList class. Since NSColorList doesn't exist for iOS I believe my only option is to build my own "ColorList" class that can create and return UIColors from a CLR file.

Is the CLR file format documented somewhere? Am I missing some other way to keep my colors in 1 place and access them from both IB and code?

Apple Docs:


Solution

  • I have done just that. I can't exactly share the all code I've written as I wrote it at work under NDA. But as a tip the solution i came up with was a pretty trivial clr exporter to a UIColor category. You can easily write a Mac OS terminal app to do this. Example:

        for (NSString *key in _colorList.allKeys) //_colorList is NSColorList
        {
            NSColor *color = [_colorList colorWithKey:key];
    
            NSNumber *red = @([color redComponent]);
            NSNumber *blue = @([color blueComponent]);
            NSNumber *green = @([color greenComponent]);
            NSNumber *alpha = @([color alphaComponent]);
    
            NSString *method = [NSString stringWithFormat:methodString, key, red, blue, green, alpha];
            [codeString appendString:method];
        }
    

    If you keep your designer to some standard of common cocoa method naming and color naming convention you can then use the CLR in the IB and use the exporter to export your category. It's not exactly what you're looking for (or I was looking for) but it certainly does the job.