使 TextView 的一半文本颜色不同于其他 50% 的文本 SWIFT

Make half of the TextView's text color Different than other 50% of the text SWIFT

我的 UITextView 中有一个大文本,我想将文本颜色的 50% 设为红色,将另外 50% 设为绿色。我在 TextView 中添加了 NSMutableAttributedString 但它适用于整个文本范围。如何将 textView 的文本分成两部分并将它们着色为红色和绿色?

let strNumber: NSString = self.text as NSString // TextView Text
        let range = (strNumber).range(of: strNumber as String)
        let attribute = NSMutableAttributedString.init(string: strNumber as String)
        attribute.addAttributes([NSAttributedString.Key.font : UIFont.systemFont(ofSize: 14) , NSAttributedString.Key.foregroundColor : UIColor.red], range: range)
        self.attributedText = attribute

尝试使用如下函数

text_lbl.attributedText = self.decorateText(txt1: "Red Color", txt2: “Blue Color”)


func decorateText(txt1:String, txt2:String)->NSAttributedString{
    let textAttributesOne = [NSAttributedStringKey.foregroundColor: UIColor.red, NSAttributedStringKey.font: UIFont(name: "Poppins-Regular", size: 12.0)!] as [NSAttributedStringKey : Any]
    let textAttributesTwo = [NSAttributedStringKey.foregroundColor: UIColor.blue, NSAttributedStringKey.font: UIFont(name: "Poppins-SemiBold", size: 14.0)!] as [NSAttributedStringKey : Any]

    let textPartOne = NSMutableAttributedString(string: txt1, attributes: textAttributesOne)
    let textPartTwo = NSMutableAttributedString(string: txt2, attributes: textAttributesTwo)

    let textCombination = NSMutableAttributedString()
    textCombination.append(textPartOne)
    textCombination.append(textPartTwo)
    return textCombination
}

您似乎有 UITextView 的扩展。以下扩展函数将使文本视图的现有属性文本变为一半红色和一半绿色。所有其他现有属性(如果有)将保留。

extension UITextView {
    func makeHalfRedGreen() {
        if let text = self.text {
            let half = text.count / 2
            let halfIndex = text.index(text.startIndex, offsetBy: half)
            let firstRange = NSRange(..<halfIndex, in: text)
            let secondRange = NSRange(halfIndex..., in: text)
            let attrTxt = NSMutableAttributedString(attributedString: attributedText)
            attrTxt.addAttribute(.foregroundColor, value: UIColor.red, range: firstRange)
            attrTxt.addAttribute(.foregroundColor, value: UIColor.green, range: secondRange)
            attributedText = attrTxt
        }
    }
}