在 UITextView 中更改特定单词的颜色

Change a specific words color in a UITextView

我在尝试什么

代码

 func textViewDidChange(_ textView: UITextView) {
    var output = " " + textView.text
    var outArray = output.components(separatedBy: " ").dropFirst()

    for W in outArray {
        if W == "//" {
            textView.textColor = UIColor.lightGray
        }
    }
}

问题

我遇到的问题是我试图仅更改 UITextView 中特定单词的颜色(例如“//”为红色,"let" 为绿色),所以我是想知道你会怎么做。

试试这个代码

import UIKit

extension String {
    func getRanges(of string: String) -> [NSRange] {
        var ranges:[NSRange] = []
        if contains(string) {
            let words = self.components(separatedBy: " ")
            var position:Int = 0
            for word in words {
                if word.lowercased() == string.lowercased() {
                    let startIndex = position
                    let endIndex = word.count
                    let range = NSMakeRange(startIndex, endIndex)
                    ranges.append(range)
                }
                position += (word.count + 1) 
            }
        }
        return ranges
    }
    func setColorToChar(_ chars: [String] , color: [UIColor]) -> NSMutableAttributedString {
        let attributedString = NSMutableAttributedString(string: self)

        if chars.count != color.count {
            fatalError("Colors are not added correctly")
        }

         //   let ranges = getRanges(of: char)
           for i in 0..<chars.count {
            let ranges = getRanges(of: chars[i])
            for range in ranges {
                attributedString.addAttributes([NSForegroundColorAttributeName: color[i]], range: range)
            }
        }

        return attributedString
    }
}

class ViewController: UIViewController,UITextViewDelegate {

   @IBOutlet weak var myTextView: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()
        myTextView.delegate = self 

    }

    func textViewDidChange(_ textView: UITextView) {

        textView.attributedText = textView.text.setColorToChar(["//","let"], color: [.red,.green])
    }


}

结果截图

您可以通过 UITextView

的扩展轻松地做到这一点
extension UITextView {
    func halfTextColorChange (fullText : String , changeText : String ) {

        let strNumber: NSString = fullText as NSString
        let range = (strNumber).range(of: changeText)
        let attribute = NSMutableAttributedString.init(string: fullText)
        attribute.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor(red: 76/255, green: 76/255, blue:76/255, alpha: 1.0) , range: range)

        self.attributedText = attribute
    }
}

用法

txtView.halfTextColorChange(fullText: "ABCXYZ", changeText: "XYZ")