Skip to content

Instantly share code, notes, and snippets.

@iamleeg
Last active December 29, 2015 03:09
Show Gist options
  • Save iamleeg/7605110 to your computer and use it in GitHub Desktop.
Save iamleeg/7605110 to your computer and use it in GitHub Desktop.
UIColor literals.
#import <UIKit/UIKit.h>
UIColor * operator"" _c(unsigned long long color)
{
unsigned long long redComponent = (color & 0xff0000 >> 16);
unsigned long long greenComponent = (color & 0x00ff00) >> 8;
unsigned long long blueComponent = color & 0xff;
float red = redComponent / 255.0;
float green = greenComponent / 255.0;
float blue = blueComponent / 255.0;
return [UIColor colorWithRed:red green:green blue:blue alpha:1.0];
}
@iamleeg
Copy link
Author

iamleeg commented Nov 22, 2013

Usage:
self.view.backgroundColor = 0x112233_c;

@iamleeg
Copy link
Author

iamleeg commented Nov 22, 2013

A colleague suggested that using bit shifts would be an alternative to all the maths on the first three lines. This is true. I didn't think of the problem that way :-)

@samdeane
Copy link

/ 255.0 rather than 256.0 surely?

@kirbyt
Copy link

kirbyt commented Nov 22, 2013

I just copied the code into my category class, and I noticed the same thing (i.e., should be / 255.0). Also, shouldn't line 5 be:

unsigned long long redComponent = (color & 0xff0000) >> 16;

@iamleeg
Copy link
Author

iamleeg commented Nov 22, 2013

Good spots, thanks.

@diederikh
Copy link

Maybe make it OS X compatible by declaring:

  #if TARGET_OS_IPHONE
  #import <UIKit/UIKit.h>
  #else
     @compatibility_alias UIColor NSColor;
   #endif

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment