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

前端之家收集整理的这篇文章主要介绍了swift – UITextView更改特定文本的文本颜色前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想更改UITextView中与数组索引匹配的特定文本的文本颜色.我能够略微修改这个 answer但不幸的是每个匹配短语的文字颜色只改变了一次.
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
}

结果

对不起,我刚注意到你的消息.这是一个工作示例(在操场上测试):
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,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,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
原文链接:https://www.f2er.com/swift/319857.html

猜你在找的Swift相关文章