Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UILabel Text Strikethrough with Color

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?

like image 894
Zia Avatar asked Mar 25 '14 19:03

Zia


4 Answers

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))
like image 117
Pantelis Proios Avatar answered Oct 22 '22 16:10

Pantelis Proios


According to the NSAttributedString UIKit Additions Reference, you can set the

NSStrikethroughColorAttributeName

attribute to an UIColor of your choice.

like image 15
Martin R Avatar answered Nov 12 '22 00:11

Martin R


Add "NSStrikethroughColorAttributeName" attribute to the string

[attributedString addAttributes:@{NSStrikethroughStyleAttributeName: @(NSUnderlineStyleSingle)
                              , NSStrikethroughColorAttributeName: [UIColor redColor]
                              , NSBackgroundColorAttributeName: [UIColor yellowColor]}

Documentation is here

like image 11
ksivamuthu Avatar answered Nov 12 '22 00:11

ksivamuthu


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))
like image 9
Ilker Baltaci Avatar answered Nov 12 '22 00:11

Ilker Baltaci