Adding strikethrough to NSAttributedString in iOS 11 with Swift

拈花ヽ惹草 提交于 2019-12-06 11:02:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!