Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to change the text color of a specific text within a UITextView which matches an index of an array. I was able to slightly modify this answer but unfortunatly the text color of each matching phrase is only changed once.

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
outcome

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

In case, someone needs it in swift 4. This is what I get from my Xcode 9 playground :).

import UIKit
import PlaygroundSupport
class MyViewController : UIViewController
{
    override func loadView()
    {
        let view = UIView()
        view.backgroundColor = .white

        let textView = UITextView()
        textView.frame = CGRect(x: 150, y: 200, width: 200, height: 20)
        textView.text = "@Kam @Jam @Tam @Ham"
        textView.textColor = .black
        view.addSubview(textView)
        self.view = view

        let query = "@"

        if let str = textView.text {
            let text = NSMutableAttributedString(string: str)
            var searchRange = str.startIndex..<str.endIndex
            while let range = str.range(of: query, options: NSString.CompareOptions.caseInsensitive, range: searchRange) {
                text.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.gray, range: NSRange(range, in: str))
                searchRange = range.upperBound..<searchRange.upperBound
            }
            textView.attributedText = text
        }
    }
}
PlaygroundPage.current.liveView = MyViewController()

I think for swift 3, you need to convert Range(String.Index) to NSRange manually like this.

 let start = str.distance(from: str.startIndex, to: range.lowerBound)
 let len = str.distance(from: range.lowerBound, to: range.upperBound)
 let nsrange = NSMakeRange(start, len)
 text.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.gray, range: nsrange)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...