Swift - 如何在纯文本的末尾附加特定的属性文本,同时不更改 TextView 上先前文本的属性

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

我尝试在纯文本的末尾附加属性文本。为了做到这一点,我想我必须将所有 textView.text 设置为属性,然后设置 textView.attributedText = 组合。但是当我这样做时,前几行的所有文本都变小了,我不明白为什么。代码如下:

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

您在创建 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