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

时间:2018-04-24 19:03:27

标签: swift 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”为绿色),所以我想知道你怎么样那样做。

2 个答案:

答案 0 :(得分:0)

试试此代码

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])
    }


}

结果截图

enter image description here

答案 1 :(得分:-1)

您可以通过对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")