问题
Having some issues getting strikethrough to work. Currently I'm doing the following:
theString.addAttributes([
NSAttributedStringKey.strikethroughStyle: NSUnderlineStyle.styleSingle.rawValue,
NSAttributedStringKey.strikethroughColor: UIColor.white
], range: NSMakeRange(0, 1))
It's not showing any sort of strikethrough though. Any ideas? I can't seem to find anything that works.
回答1:
I use this to strike through a text in Xcode9/iOS11/Swift4 env
let strokeEffect: [NSAttributedStringKey : Any] = [
NSAttributedStringKey.strikethroughStyle: NSUnderlineStyle.styleSingle.rawValue,
NSAttributedStringKey.strikethroughColor: UIColor.red,
]
let strokeString = NSAttributedString(string: "text", attributes: strokeEffect)
回答2:
swift 4.1
attributedText.addAttributes([
NSAttributedStringKey.strikethroughStyle:NSUnderlineStyle.styleSingle.rawValue, NSAttributedStringKey.strikethroughColor:UIColor.black],
range: NSMakeRange(0, attributedText.length))
回答3:
I am sharing latest updates. For Swift4, iOS 11.3
attributedText.addAttributes([
NSStrikethroughStyleAttributeName:
NSUnderlineStyle.styleSingle.rawValue,
NSStrikethroughColorAttributeName:
UIColor.black], range: textRange)
回答4:
swift 4.2
let mutPricesString : NSMutableAttributedString = NSMutableAttributedString()
var attrPrice_1 : NSAttributedString = NSAttributedString()
var attrPrice_2 : NSAttributedString = NSAttributedString()
attrPrice_1 = NSAttributedString(string: "14000 KD", attributes:
[NSAttributedString.Key.strikethroughStyle: NSUnderlineStyle.single.rawValue,
NSAttributedString.Key.foregroundColor: UIColor.lightGray,
NSAttributedString.Key.font: ARFont.Regular(fontSize: 15)])
attrPrice_2 = NSAttributedString(string: " 12460 KD", attributes:
[NSAttributedString.Key.foregroundColor: UIColor.black,
NSAttributedString.Key.font: ARFont.Semibold(fontSize: 17)])
mutPricesString.append(attrPrice_1)
mutPricesString.append(attrPrice_2)
lbl.attributedText = mutFollowersString
ANSWER :
回答5:
Swift 5.1
let attributedText : NSMutableAttributedString = NSMutableAttributedString(string: "Your Text")
attributedText.addAttributes([
NSAttributedString.Key.strikethroughStyle: NSUnderlineStyle.single.rawValue,
NSAttributedString.Key.strikethroughColor: UIColor.lightGray,
NSAttributedString.Key.font : UIFont.systemFont(ofSize: 12.0)
], range: NSMakeRange(0, attributedText.length))
来源:https://stackoverflow.com/questions/49417952/adding-strikethrough-to-nsattributedstring-in-ios-11-with-swift