UILabel with text struck through

2020-01-25 13:31发布

问题:

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

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

回答1:

SWIFT 4 UPDATE CODE

let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string: "Your Text")
    attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: 2, range: NSMakeRange(0, 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.



回答2:

In Swift, using the enum for single strikethrough line style:

let attrString = NSAttributedString(string: "Label Text", attributes: [NSStrikethroughStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue])
label.attributedText = attrString

Additional strikethrough styles (Remember to access the enum using .rawValue):

  • NSUnderlineStyle.StyleNone
  • NSUnderlineStyle.StyleSingle
  • NSUnderlineStyle.StyleThick
  • NSUnderlineStyle.StyleDouble

Strikethrough patterns (to be OR-ed with the style):

  • NSUnderlineStyle.PatternDot
  • NSUnderlineStyle.PatternDash
  • NSUnderlineStyle.PatternDashDot
  • NSUnderlineStyle.PatternDashDotDot

Specify that the strikethrough should only be applied across words (not spaces):

  • NSUnderlineStyle.ByWord


回答3:

I prefer NSAttributedString rather than NSMutableAttributedString for this simple case:

NSAttributedString * title =
    [[NSAttributedString alloc] initWithString:@"$198"
                                    attributes:@{NSStrikethroughStyleAttributeName:@(NSUnderlineStyleSingle)}];
[label setAttributedText:title];

Constants for specifying both the NSUnderlineStyleAttributeName and NSStrikethroughStyleAttributeName attributes of an attributed string:

typedef enum : NSInteger {  
  NSUnderlineStyleNone = 0x00,  
  NSUnderlineStyleSingle = 0x01,  
  NSUnderlineStyleThick = 0x02,  
  NSUnderlineStyleDouble = 0x09,  
  NSUnderlinePatternSolid = 0x0000,  
  NSUnderlinePatternDot = 0x0100,  
  NSUnderlinePatternDash = 0x0200,  
  NSUnderlinePatternDashDot = 0x0300,  
  NSUnderlinePatternDashDotDot = 0x0400,  
  NSUnderlineByWord = 0x8000  
} NSUnderlineStyle;  


回答4:

SWIFT CODE

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

then:

yourLabel.attributedText = attributeString

Thanks to Prince answer ;)



回答5:

Strikethrough in Swift 4.0

let attributeString =  NSMutableAttributedString(string: "Your Text")

attributeString.addAttribute(NSAttributedStringKey.strikethroughStyle,
                                 value: NSUnderlineStyle.styleSingle.rawValue,
                                 range: NSMakeRange(0, attributeString.length))
self.yourLabel.attributedText = attributeString

It worked for me like a charm.

Use it as extension

extension String {
    func strikeThrough() -> NSAttributedString {
        let attributeString =  NSMutableAttributedString(string: self)
        attributeString.addAttribute(NSAttributedStringKey.strikethroughStyle, value: NSUnderlineStyle.styleSingle.rawValue, range: NSMakeRange(0,attributeString.length))
        return attributeString
    }
}

Call like this

myLabel.attributedText = "my string".strikeThrough()


回答6:

SWIFT 4

    let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string: "Your Text Goes Here")
    attributeString.addAttribute(NSAttributedStringKey.strikethroughStyle, value: NSUnderlineStyle.styleSingle.rawValue, range: NSMakeRange(0, attributeString.length))
    self.lbl_productPrice.attributedText = attributeString

Other method is to used String Extension
Extension

extension String{
    func strikeThrough()->NSAttributedString{
        let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string: self)
        attributeString.addAttribute(NSAttributedStringKey.strikethroughStyle, value: NSUnderlineStyle.styleSingle.rawValue, range: NSMakeRange(0, attributeString.length))
        return attributeString
    }
}

Calling the function : Used it like so

testUILabel.attributedText = "Your Text Goes Here!".strikeThrough()

Credit to @Yahya - update Dec 2017
Credit to @kuzdu - update Aug 2018



回答7:

You can do it in IOS 6 using NSMutableAttributedString.

NSMutableAttributedString *attString=[[NSMutableAttributedString alloc]initWithString:@"$198"];
[attString addAttribute:NSStrikethroughStyleAttributeName value:[NSNumber numberWithInt:2] range:NSMakeRange(0,[attString length])];
yourLabel.attributedText = attString;


回答8:

Strike out UILabel text in Swift iOS. PLease try this it's working for me

let attributedString = NSMutableAttributedString(string:"12345")
                      attributedString.addAttribute(NSAttributedStringKey.baselineOffset, value: 0, range: NSMakeRange(0, attributedString.length))
                      attributedString.addAttribute(NSAttributedStringKey.strikethroughStyle, value: NSNumber(value: NSUnderlineStyle.styleThick.rawValue), range: NSMakeRange(0, attributedString.length))
                      attributedString.addAttribute(NSAttributedStringKey.strikethroughColor, value: UIColor.gray, range: NSMakeRange(0, attributedString.length))

 yourLabel.attributedText = attributedString

You can change your "strikethroughStyle" like styleSingle, styleThick,styleDouble



回答9:

For anyone looking on how to do this in a tableview cell (Swift) you have to set the .attributeText like this:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("TheCell")!

    let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string: message)
    attributeString.addAttribute(NSStrikethroughStyleAttributeName, value: 2, range: NSMakeRange(0, attributeString.length))

    cell.textLabel?.attributedText =  attributeString

    return cell
    }

If you want to remove the strikethrough do this otherwise it will stick around!:

cell.textLabel?.attributedText =  nil


回答10:

Swift 5

extension String {

  /// Apply strike font on text
  func strikeThrough() -> NSAttributedString {
    let attributeString = NSMutableAttributedString(string: self)
    attributeString.addAttribute(
      NSAttributedString.Key.strikethroughStyle,
      value: 1,
      range: NSRange(location: 0, length: attributeString.length))

      return attributeString
     }
   }

Example:

someLabel.attributedText = someText.strikeThrough()


回答11:

Swift 4.2

let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string: product.price)

attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: NSUnderlineStyle.single.rawValue, range: NSMakeRange(0, attributeString.length))

lblPrice.attributedText = attributeString


回答12:

Use below code

NSString* strPrice = @"£399.95";

NSMutableAttributedString *titleString = [[NSMutableAttributedString alloc] initWithString:strPrice];

[finalString addAttribute: NSStrikethroughStyleAttributeName value:[NSNumber numberWithInteger: NSUnderlineStyleSingle] range: NSMakeRange(0, [titleString length])];
self.lblOldPrice.attributedText = finalString;   


回答13:

For those who face issue with multi line text strike

    let attributedString = NSMutableAttributedString(string: item.name!)
    //necessary if UILabel text is multilines
    attributedString.addAttribute(NSBaselineOffsetAttributeName, value: 0, range: NSMakeRange(0, attributedString.length))
     attributedString.addAttribute(NSStrikethroughStyleAttributeName, value: NSNumber(value: NSUnderlineStyle.styleSingle.rawValue), range: NSMakeRange(0, attributedString.length))
    attributedString.addAttribute(NSStrikethroughColorAttributeName, value: UIColor.darkGray, range: NSMakeRange(0, attributedString.length))

    cell.lblName.attributedText = attributedString


回答14:

Create String extension and add below method

static func makeSlashText(_ text:String) -> NSAttributedString {


 let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string: text)
        attributeString.addAttribute(NSStrikethroughStyleAttributeName, value: 2, range: NSMakeRange(0, attributeString.length))

return attributeString 

}

then use for your label like this

yourLabel.attributedText = String.makeSlashText("Hello World!")


回答15:

This is the one you can use in Swift 4 because NSStrikethroughStyleAttributeName has been changed to NSAttributedStringKey.strikethroughStyle

let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string: "Your Text")

attributeString.addAttribute(NSAttributedStringKey.strikethroughStyle, value: 2, range: NSMakeRange(0, attributeString.length))

self.lbl.attributedText = attributeString


回答16:

Change the text property to attributed and select the text and right click to get the font property. Click on the strikethrough.