小编典典

UITextView更改特定文本的文本颜色

swift

我想更改与数组索引匹配的UITextView中特定文本的文本颜色。我能够略微修改此答案,但不幸的是,每个匹配短语的文本颜色仅更改了一次。

var chordsArray = ["Cmaj", "Bbmaj7"]
func getColoredText(textView: UITextView) -> NSMutableAttributedString {
    let text = textView.text
    let string:NSMutableAttributedString = NSMutableAttributedString(string: text)
    let words:[String] = text.componentsSeparatedByString(" ")
    for word in words {
        if (chordsArray.contains(word)) {
            let range:NSRange = (string.string as NSString).rangeOfString(word)
            string.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: range)
        }
    }
    chords.attributedText = string
    return string
}

阅读 414

收藏
2020-07-07

共1个答案

小编典典

抱歉,我刚注意到您的消息。这是一个工作示例(在操场上测试):

import UIKit


func apply (string: NSMutableAttributedString, word: String) -> NSMutableAttributedString {
    let range = (string.string as NSString).rangeOfString(word)
    return apply(string, word: word, range: range, last: range)
}

func apply (string: NSMutableAttributedString, word: String, range: NSRange, last: NSRange) -> NSMutableAttributedString {
    if range.location != NSNotFound {
        string.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: range)
        let start = last.location + last.length
        let end = string.string.characters.count - start
        let stringRange = NSRange(location: start, length: end)
        let newRange = (string.string as NSString).rangeOfString(word, options: [], range: stringRange)
        apply(string, word: word, range: newRange, last: range)
    }
    return string
}

var chordsArray = ["Cmaj", "Bbmaj7"]
var text = "Cmaj Bbmaj7 I Love Swift Cmaj Bbmaj7 Swift"
var newText = NSMutableAttributedString(string: text)

for word in chordsArray {
    newText = apply(newText, word: word)
}

newText
2020-07-07