Search code examples
iosswiftcocoa-touchuilabelstrikethrough

How can I create a UILabel with strikethrough text?


I want to create a UILabel in which the text is like this

enter image description here

How can I do this? When the text is small, the line should also be small.


Solution

  • SWIFT 5 UPDATE CODE

    let attributeString: NSMutableAttributedString = NSMutableAttributedString(string: "Your Text")
        attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: 2, range: NSRange(location: 0, length: attributeString.length))
    

    then:

    yourLabel.attributedText = attributeString
    

    To make some part of string to strike then provide range

    let somePartStringRange = (yourStringHere as NSString).range(of: "Text")
    attributeString.addAttribute(NSStrikethroughStyleAttributeName, value: 2, range: somePartStringRange)
    

    Objective-C

    In iOS 6.0 > UILabel supports NSAttributedString

    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:@"Your String here"];
    [attributeString addAttribute:NSStrikethroughStyleAttributeName
                            value:@2
                            range:NSMakeRange(0, [attributeString length])];
    

    Swift

    let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string: "Your String here")
    attributeString.addAttribute(NSStrikethroughStyleAttributeName, value: 2, range: NSMakeRange(0, attributeString.length))
    

    Definition :

    - (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)aRange
    

    Parameters List:

    name : A string specifying the attribute name. Attribute keys can be supplied by another framework or can be custom ones you define. For information about where to find the system-supplied attribute keys, see the overview section in NSAttributedString Class Reference.

    value : The attribute value associated with name.

    aRange : The range of characters to which the specified attribute/value pair applies.

    Then

    yourLabel.attributedText = attributeString;
    

    For lesser than iOS 6.0 versions you need 3-rd party component to do this. One of them is TTTAttributedLabel, another is OHAttributedLabel.