How to Create a UIColor Object From A Hex Value

In this post I’ll demonstrate how to create a category of the UIColor class to add a method for creating a UIColor object from a hex value. That’s a mouthful – if you need to create a UIColor object from a hex string, read on…

Assume you have the value @”0A5CEA” (an NSString object that holds a hex value) and need a UIColor object that represents the value of the string. With the code below, creating the UIColor object is as easy as:

UIColor *color = [UIColor colorwithHexString:@"0A5CEA" alpha:.9];

Notice that I’ve also provided a parameter to set the alpha value.

Continue reading

Adding Properties to a Category Using Associated Objects

Categories are a cool feature of Objective-C that allow you to extend existing classes with extra methods. This helps you to write really clean code by adding utility methods directly to the classes they relate to, so they can be called in a natural, object-oriented way.

A typical example of a category method is given below. Here we add an isNumeric method to NSString:

Continue reading