Archive for November, 2008

Creating UIColor objects from hex values

It’s pretty inconvenient to create UIColor objects while developing apps for the iPhone, as you need to specific separate values for the RGB parts: red, green, blue.

I found a trick online a few weeks ago on how to automatically generate that code, by simply using a macro:

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

The usage looks something like this:

- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (nil == cell) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"cell"] autorelease];
    cell.textColor = UIColorFromRGB(0x333333);
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.text = @"Testing 1 2 3";

Hope that’s useful to someone.