Swift-如何在纯文本末尾附加特定的属性文本,同时不更改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