I want to use NSAttributedString
in my project, but when I\'m trying to set color, which isn\'t from the standard set (redColor
, blackColor
Please try the code
[attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:77.0/255.0f green:104.0/255.0f blue:159.0/255.0f alpha:1.0] range:NSMakeRange(0, attributedString.length)];
like
Label.textColor=[UIColor colorWithRed:77.0/255.0f green:104.0/255.0f blue:159.0/255.0f alpha:1.0];
UIColor's RGB components are scaled between 0 and 1, not up to 255.
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
red The red component of the color object, specified as a value from 0.0 to 1.0.
green The green component of the color object, specified as a value from 0.0 to 1.0.
blue The blue component of the color object, specified as a value from 0.0 to 1.0.
alpha The opacity value of the color object, specified as a value from 0.0 to 1.0.
Reference here.
UIColor
uses a range from 0 to 1.0, not integers to 255.. Try this:
// create color
UIColor *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)];
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)];
Since @Jaswanth Kumar asked, here's the Swift
version from LSwift:
extension UIColor {
convenience init(rgb:UInt, alpha:CGFloat = 1.0) {
self.init(
red: CGFloat((rgb & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgb & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgb & 0x0000FF) / 255.0,
alpha: CGFloat(alpha)
)
}
}
Usage: let color = UIColor(rgb: 0x112233)