Last active
December 29, 2015 03:09
-
-
Save iamleeg/7605110 to your computer and use it in GitHub Desktop.
UIColor literals.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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]; | |
} |
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 :-)
/ 255.0 rather than 256.0 surely?
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;
Good spots, thanks.
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
Usage:
self.view.backgroundColor = 0x112233_c;