Search code examples
iosswifttextviewstrikethrough

How to keep strikethrough when adding a new one in a textview? The strikethrough jumps to the newest highlighted word


I have a textview and it's set as an attributed text. When I use this code and click my button to strikethrough it will strikethrough the highlighted section perfectly. But when I highlight another section and click strikethrough it clears the first one and the new highlighted section I strikethrough gets the line.

let attributeString: NSMutableAttributedString = NSMutableAttributedString(string: textView.text)
attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: NSUnderlineStyle.single.rawValue, range: textView.selectedRange)

textView.attributedText = attributeString
textView.font = UIFont(name: "Helvetica Neue", size: 16.0)

How can I keep it for all sections? Where it won't clear out unless I clear it myself? I guess I didn't realize how would I clear it also?


Solution

  • You create a new attributed string with no attributes, then you add the one strikethrough.

    Instead, update the existing attributed string.

    let attributeString: NSMutableAttributedString = NSMutableAttributedString(attributedString: textView.attributedText)