How do I create a UIColor from RGBA? How do I create a UIColor from RGBA? ios ios

How do I create a UIColor from RGBA?


Your values are incorrect, you need to divide each color value by 255.0.

[UIColor colorWithRed:66.0f/255.0f                green:79.0f/255.0f                 blue:91.0f/255.0f                alpha:1.0f];

The docs state:

+ (UIColor *)colorWithRed:(CGFloat)red                    green:(CGFloat)green                     blue:(CGFloat)blue                    alpha:(CGFloat)alpha

Parameters

redThe red component of the color object, specified as a value from 0.0 to 1.0.

greenThe green component of the color object, specified as a value from 0.0 to 1.0.

blueThe blue component of the color object, specified as a value from 0.0 to 1.0.

alphaThe opacity value of the color object, specified as a value from 0.0 to 1.0.

Reference here.


One of my favourite macros, no project without:

#define RGB(r, g, b) [UIColor colorWithRed:(float)r / 255.0 green:(float)g / 255.0 blue:(float)b / 255.0 alpha:1.0]#define RGBA(r, g, b, a) [UIColor colorWithRed:(float)r / 255.0 green:(float)g / 255.0 blue:(float)b / 255.0 alpha:a]

Using like:

[attributedString addAttribute:NSForegroundColorAttributeName                         value:RGB(66, 79, 91)                         range:NSMakeRange(0, attributedString.length)];


UIColor uses a range from 0 to 1.0, not integers to 255.. Try this:

// create colorUIColor *color = [UIColor colorWithRed:66/255.0                                 green:79/255.0                                  blue:91/255.0                                 alpha:1];// use in attributed string[attributedString addAttribute:NSForegroundColorAttributeName                         value:color                         range:NSMakeRange(0, attributedString.length)];