Search code examples
iosobjective-cswiftnsattributedstringuicolor

NSAttributedString: How to mimic opacity or alpha equivalent using color


I am using NSAttributedString for a button title and would like to be able to "grey out" or lower the alpha or capacity of certain text. NSAttributedString does not appear to allow you to modify the opacity or alpha value of the text but does let you adjust the color using:

NSMutableAttributedString *text = 
 [[NSMutableAttributedString alloc] 
   initWithAttributedString: label.attributedText];
[text addAttribute:NSForegroundColorAttributeName 
             value:[UIColor redColor] 
             range:NSMakeRange(10, 1)];

or:

let range = (mainString as NSString).range(of: stringToColor)
let mutableAttributedString = NSMutableAttributedString.init(string: mainString)
mutableAttributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red, range: range)

In this case, the starting color is System Blue. Is there any formula that would allow me to modify the system color to the equivalent of an alpha value (or opacity) of 0.5?

Thanks for any suggestions.


Solution

  • You can change any color alpha using

    UIColor.red.withAlphaComponent(0.5)
    

    Of course, you have to know the original color.

    There is no universal alpha modifier.