0

For the first time, I am working with attributed strings so please bear with me!

I have spent a lot of time on SO looking at various attributed string answers but I'm still not convinced I am doing the right thing and would appreciate any advice.

I have created an NSMutableAttributed String (var attributedText) and a simple UIView with a TextView and 2 buttons which should in theory turn any part of highlighted text in the UITextView to bold or italic.

In ViewDidLoad, I have simply added some dummy text and added a couple of attributes to the text such as line spacing and font color. When the view appears all looks as expected.

If I highlight a portion of text and tap the bold button, it returns an attribute and adds it to attributedText and then to the textView (textView.attributedText = attributedText).

The following is my return function:

func boldText() -> Dictionary<NSAttributedString.Key, Any>  {
    let attributes: [NSAttributedString.Key: Any] = [
        .font: UIFont.systemFont(ofSize: 15, weight: .bold),
    ]
    return attributes
}

Now, here's where things get confusing. If I manually type some text in the UTextView and highlight a portion of that text and tap the Bold button, the app will crash due to the text being out of range, this makes sense as my attributedText variable is only holding the previous dummy text I added in ViewDidLoad and not the new text I have typed.

So my question is, how do I add the new text I typed to the attributedText variable without messing up all the other formatting that was already part of that text? If I just add the textView text to the variable:

attributedText = NSMutableAttributedString(string: "\(textView.text!)" )

Then obviously it simply overwrites anything that was held in the attributedText variable previously which in turn removes all formatting.

Am I on the right lines in the fact that every time change happens in the textView I need to somehow update my attributedText variable or should I be using a different approach altogether?

Chris
  • 247
  • 1
  • 4
  • 17
  • 1
    Why not retrieving the `attributedText` property of the `UITextView` instead: `attributedText = NSMutableAttributedString(string: "\(textView.text!)" )` => `attributedText = textView.attributedText` There are plenty of delegate method that will tell you when it's updated too. – Larme Aug 25 '20 at 09:25
  • Thank you @Larme - that was easy, I have no idea why I didn't think of that. If you would like to add it as an answer, I'll make sure to mark it as correct....thank you! – Chris Aug 25 '20 at 10:32

0 Answers0