I am using the following code to strike through the text
NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:(text ? text : @"")];
[attributeString addAttribute:NSStrikethroughStyleAttributeName
value:@2
range:NSMakeRange(0, [attributeString length])];
label.attributedText = attributeString;
The text has white color so the strikethrough line is also white. I would like to change that to red. How can I do so?
SWIFT 4.2
@llker Baltaci 's answer update for Swift 4.2
let attributedString = NSMutableAttributedString(string: "0,91 €")
attributedString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: NSNumber(value: NSUnderlineStyle.single.rawValue), range: NSMakeRange(0, attributedString.length))
attributedString.addAttribute(NSAttributedString.Key.strikethroughColor, value: UIColor.darkGray, range: NSMakeRange(0, attributedString.length))
According to the NSAttributedString UIKit Additions Reference, you can set the
NSStrikethroughColorAttributeName
attribute to an UIColor
of your choice.
Add "NSStrikethroughColorAttributeName" attribute to the string
[attributedString addAttributes:@{NSStrikethroughStyleAttributeName: @(NSUnderlineStyleSingle)
, NSStrikethroughColorAttributeName: [UIColor redColor]
, NSBackgroundColorAttributeName: [UIColor yellowColor]}
Documentation is here
SWIFT 3.x
To strikethrough a text label with color you need 2 attributes, one for the NSStrikethroughStyleAttributeName one for the NSStrikethroughColorAttributeName. I find it more readable.
let attributedString = NSMutableAttributedString(string: "0,91 €")
attributedString.addAttribute(NSStrikethroughStyleAttributeName, value: NSNumber(value: NSUnderlineStyle.styleSingle.rawValue), range: NSMakeRange(0, attributedString.length))
attributedString.addAttribute(NSStrikethroughColorAttributeName, value: UIColor.red, range: NSMakeRange(0, attributedString.length))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With