1

I have one UILabel which shows strikethrough text (e.g. text). It was working fine till iOS 13. In iOS 14, that strikethrough line is not showing, i.e. instead of 'text', it is coming as 'text'. This is the code I used:

let totalString: String = "some text"
let strikeString: String = "text" //string to be made strikethrough
let totalNsString = totalString as NSString
let attributeString =  NSMutableAttributedString(string: totalString)
attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: 2, range: totalNsString.range(of: strikeString))
label.attributedText = attributeString

Desired Output:

some text

Current Outout:

some text

Can anyone please tell me is there anything I need to change or anything else. TIA.

Arnab
  • 4,216
  • 2
  • 28
  • 50

4 Answers4

2

Adding baselineOffset with value 0 to the attributed string brings back the strikethrough line. More details can be found on apple dev forum and this SO thread.

attributeString.addAttribute(NSAttributedString.Key.baselineOffset, value: 0, range: totalNsString.range(of: strikeString))
Arnab
  • 4,216
  • 2
  • 28
  • 50
0

Can't reproduce. I copied your code without any change and ran it, and this is what I see in the simulator:

enter image description here

That is what I would expect to see, and what you claim you want to see. So if you are not seeing that, it is due to some other cause. Maybe label is not the UILabel you think it is. Maybe other code is coming along and changing the text. But whatever the reason, it's nothing to do with the question as posed.

(As a matter of practice and legibility, it would be better to say NSUnderlineStyle.thick.rawValue instead of 2. But that has nothing to do with the issue here.)

matt
  • 515,959
  • 87
  • 875
  • 1,141
0

The solution is to use strikethroughStyle, but also to set strikethroughColor:

let attributeString: NSMutableAttributedString = NSMutableAttributedString(string: text, attributes: [:])
attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle,
                                     value: NSUnderlineStyle.single.rawValue,
                                     range: NSRange(location: 0, length: attributeString.length))
attributeString.addAttribute(NSAttributedString.Key.strikethroughColor,
                                     value: UIColor.black,
                                     range: NSRange(location: 0, length: attributeString.length))
Andrey Dyatkov
  • 127
  • 1
  • 6
0

I had same problem in iOS 14. My problem was that I was passing cgColor to the attribute .strikethrough color. In this attribute you need use only UIColor.

Leon Jakonda
  • 83
  • 1
  • 6