我有uitextviewtext_receity,我用不同的颜色写文本。在我的解决方案中,我需要添加彩色文本,但原始文本和颜色必须保持不变。是否有一种方法可以正确地获得原始文本的颜色?
var toastcolor: UIColor = UIColor.black
var toast: String = "TEST..."
if ChodButtonisOn == true {
toastcolor = UIColor(red: 118/255, green: 110/255, blue: 38/255, alpha: 1.0)
} else {
if HalfButtonisOn == true {
toastcolor = UIColor(red: 240/255, green: 127/255, blue: 18/255, alpha: 1.0)
}
}
let text1 = NSMutableAttributedString(string: text_recepty.text!)
let attr2 = [NSAttributedString.Key.foregroundColor: toastcolor]
let text2 = NSAttributedString(string: toast + "n", attributes: attr2)
text1.append(text2)
text_recepty.attributedText = text1
```
您需要从UITextView中获取attributedText
,然后添加新的文本到它,如:
let existingText = myTextView.attributedText
let mutableText = NSAttributedString(attributedString: existingText)
// Then add your text
查看NSMutableAttributedString文档,了解如何完成最后一部分。