UILabel Text Strikethrough with Color
Asked Answered
V

5

13

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?

V1 answered 25/3, 2014 at 19:36 Comment(0)
O
15

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

NSStrikethroughColorAttributeName

attribute to an UIColor of your choice.

Occidental answered 25/3, 2014 at 19:42 Comment(1)
Thank you. This did it [attributeString addAttribute:NSStrikethroughColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, [attributeString length])];V1
Q
11

Add "NSStrikethroughColorAttributeName" attribute to the string

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

Documentation is here

Quoit answered 25/3, 2014 at 19:43 Comment(1)
This page is nolonger availableBabbette
I
9

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))
Indocile answered 3/2, 2017 at 7:45 Comment(0)
L
9

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))
Limousine answered 18/10, 2018 at 10:55 Comment(0)
J
5

In Swift:

attributeString.addAttribute(NSStrikethroughColorAttributeName, value: UIColor.redColor(), range: NSMakeRange(0, attributeString.length))
Jesu answered 16/5, 2016 at 7:5 Comment(1)
Please indent code blocks (use four spaces or select the code & click the {} button on the editor toolbar).Cessionary

© 2022 - 2024 — McMap. All rights reserved.