[swift]UITextView 更改特定文本的文本颜色

标签: UITextView Swift
发布时间: 2016/5/8 1:04:15
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我想要改变 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
}

结果
outcome

解决方法 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
官方微信
官方QQ群
31647020