How can I create a UILabel with strikethrough text?
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.
UILabel Text Strikethrough with Color
According to the NSAttributedString UIKit Additions Reference, you can set the
NSStrikethroughColorAttributeName
attribute to an UIColor
of your choice.
How to strikethrough a portion of the text
Attributed strings are quite a hassle to create indeed.
This clever code extends NSAttributedString
with a .composing(_:)
method, I found it on GitHub (see copyright notice at the bottom): https://github.com/vincent-pradeilles/NSAttributedStringBuilder. It uses result builders (nee function builders).
@_functionBuilder
public class NSAttributedStringBuilder {
public static func buildBlock(_ components: NSAttributedString...) -> NSAttributedString {
let result = NSMutableAttributedString(string: "")
return components.reduce(into: result) { (result, current) in result.append(current) }
}
}
extension NSAttributedString {
public class func composing(@NSAttributedStringBuilder _ parts: () -> NSAttributedString) -> NSAttributedString {
return parts()
}
}
With this extension, you can build your attributed string like this:
let attributedString = NSAttributedString.composing {
NSAttributedString(string: "Buy this course for ")
NSAttributedString(string: "$19.99", attributes: [.strikethroughStyle : NSUnderlineStyle.single.rawValue])
NSAttributedString(string: ", $5.99")
}
Then you assign the attributed string to the UILabel
's attributedText
property, of course.
This should be possible to use for any attribute.
Note that it will need to be updated for Swift 5.3 (I don't have it yet) since it predates the final nomenclature of the result builder language feature. So basically you'll need to replace @_functionBuilder
with @resultBuilder
if I'm not mistaken.
Since this is not my code and it's released under the MIT license, I guess I have to reprint the notice here:
MIT License
Copyright (c) 2019 Vincent Pradeilles
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
UILabel Strikethrough
This is an old question and newer information is available.
Starting in iOS 6, we have NSAttributedString.
For pre iOS 6, I would look at TTTAttributedLabel
UILabel text struck through angle
All you need to do is just trim the label width to content size.
testLabel.text = "Tk 1,750"
testLabel.frame.size.width = myLabel.intrinsicContentSize.width
and then use as told by @fzh
testLabel.addSlantLine(slantLineColor: UIColor.lightGray,
slantLineWidth: 2,
startPoint: CGPoint(x: 0, y: testLabel.frame.height - 2),
endPoint: CGPoint(x: testLabel.frame.width, y: 2))
Note:
Trim after text update
UILabel, TextField with overstrike character
You can use NSAttributedString
, and set the below attribute:
let att = NSMutableAttributedString(string: "kfill")
att.addAttribute(.kern, value: -7, range: NSRange(location: 0, length: 1))
label.attributedText = att
You can change the range
and value
if you wish to achieve different results.
Swift: strikethroughStyle For Label (Middle Delete Line For Label)
Use attributeString
Screenshot
Code
NSDictionary * attribtues = @{NSStrikethroughStyleAttributeName:@(NSUnderlineStyleSingle),
NSStrikethroughColorAttributeName:[UIColor redColor]};
NSAttributedString * attr = [[NSAttributedString alloc] initWithString:@"label" attributes:attribtues];
self.label.attributedText = attr;
Related Topics
iOS Nsdate() Returns Incorrect Time
Filemanager Cannot Find Audio File
Error: Initializer for Conditional Binding Must Have Optional Type, Not 'String'
How to Change Wkwebview or Uiwebview Default Font
Using Nsuserdefaults with Xcode 8 and iOS 10
Switch Cameras with Avcapturesession
Uibutton Fails to Properly Register Touch in Bottom Region of iPhone Screen
iPhone Gps in Background Never Resumes After Pause
How to Create Custom Mkannotationview and Custom Annotation Title and Subtitle
Swift: Can't Get Nsdate Dateformatter Right
Realmswift: Convert Results to Swift Array
iOS UI Testing on an Isolated View
What Are the Device-Width CSS Viewport Sizes of the Iphone6 and iPhone 6 Plus
Uitableview Checkmark Only One Row at a Time
Launch Apple Mail App from Within My Own App