Search code examples
iosnsattributedstringstrikethrough

I want my text strike through extend on whitespace


I use NSAttributeString to set strike through on my text, I want it extend on whitespace.

I already set the correct range, but the strike through only cover the text characters. The strike through is ignore the whitespace unless I add some non-empty text before and after it.

How can I make the strike through extend on whitespace without extra text?

enter image description here


Solution

  • I haven't found any solution but with your last option means adding first and last character as . with space you can try one thing. Either set the NSForegroundColorAttributeName of that first and last character to your background color of label or set the NSFontAttributeName with UIFont.systemFont(ofSize: 0.1). So it will be goes like this. You haven't specify your answer language so i'm posting answer in latest Swift 3.

    let attributedText = NSMutableAttributedString(string: self.lbl.text!)
    attributedText.addAttributes([NSStrikethroughStyleAttributeName: 2], range: NSMakeRange(0, self.lbl.text!.characters.count))
    self.lbl.attributedText = attributedText
    

    Before using NSForegroundColorAttributeName & NSFontAttributeName enter image description here

    Now you can use either NSForegroundColorAttributeName or NSFontAttributeName to hide first and last dot(.) character.

    let attributedText = NSMutableAttributedString(string: self.lbl.text!)
    attributedText.addAttributes([NSStrikethroughStyleAttributeName: 2], range: NSMakeRange(0, self.lbl.text!.characters.count))
    attributedText.addAttributes([NSForegroundColorAttributeName: UIColor.white], range: NSMakeRange(0, 1))
    attributedText.addAttributes([NSForegroundColorAttributeName: UIColor.white], range: NSMakeRange(self.lbl.text!.characters.count - 1, 1))
    //Or either Set NSFontAttributeName instead of NSForegroundColorAttributeName
    //attributedText.addAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 0.1)], range: NSMakeRange(0, 1))
    //attributedText.addAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 0.1)], range: NSMakeRange(self.lbl.text!.characters.count - 1, 1))
    self.lbl.attributedText = attributedText
    

    After using NSForegroundColorAttributeName or NSFontAttributeName enter image description here