Search code examples
swiftappendnsattributedstring

Swift - How to append a specific attributed text at the end of a plain text, while not changing the attributes of the previous text on a TextView


I try to append attributed text at the end of a plain text. In order to do this, I think I have to make all the textView.text as attributed and then set the textView.attributedText = combination. But when I do this, all the text at the previous lines get smaller font size, I didn't understand why. The code is below:

let attributedString = NSMutableAttributedString(string: "\nANS = " + resultt + "\n")
attributedString.addAttribute(.font, value: UIFont.boldSystemFont(ofSize: textView.font!.pointSize), range: NSRange(location: 0, length: 6))
let combination = NSMutableAttributedString(string: textView.text)
combination.append(attributedString)
textView.attributedText = combination

Solution

  • You lost the attributed data when creating combination.

    let attributedString = NSMutableAttributedString(string: "\nANS = " + resultt + "\n")
    attributedString.addAttribute(.font, value: UIFont.boldSystemFont(ofSize: textView.font!.pointSize), range: NSRange(location: 0, length: 6))
    // Pass the attributed string, not the plain one
    let combination = NSMutableAttributedString(attributedString: textView.attributedText)
    combination.append(attributedString)
    textView.attributedText = combination