Search code examples
iosswiftnsstringnsmutableattributedstring

Color all occurrences of string in swift


This code

var textSearch="hi"
var textToShow="hi hihi hi" 
var rangeToColor = (textToShow as NSString).rangeOfString(textSearch)
var attributedString = NSMutableAttributedString(string:textToShow)
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.yellowColor() , range: rangeToColor)
TextView.attributedText=attributedString

gives me NSRange to color a string inside the TextView. The problem is that I only returns the first occurrence. If the word contains "hi hihi hi" only the first "hi" is colored. How can I get all occurrences of the string?


Solution

  • Swift 5

    let attrStr = NSMutableAttributedString(string: "hi hihi hey")
    let inputLength = attrStr.string.count
    let searchString = "hi"
    let searchLength = searchString.characters.count
    var range = NSRange(location: 0, length: attrStr.length)
    
    while (range.location != NSNotFound) {
        range = (attrStr.string as NSString).range(of: searchString, options: [], range: range)
        if (range.location != NSNotFound) {
            attrStr.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.yellow, range: NSRange(location: range.location, length: searchLength))
            range = NSRange(location: range.location + range.length, length: inputLength - (range.location + range.length))
        }
    }
    

    Swift 3

    let attrStr = NSMutableAttributedString(string: "hi hihi hey")
    let inputLength = attrStr.string.characters.count
    let searchString = "hi"
    let searchLength = searchString.characters.count
    var range = NSRange(location: 0, length: attrStr.length)
    
    while (range.location != NSNotFound) {
        range = (attrStr.string as NSString).range(of: searchString, options: [], range: range)
        if (range.location != NSNotFound) {
            attrStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.yellow(), range: NSRange(location: range.location, length: searchLength))
            range = NSRange(location: range.location + range.length, length: inputLength - (range.location + range.length))
        }
    }
    

    Swift 2

    let attrStr = NSMutableAttributedString(string: "hi hihi hey")
    let inputLength = attrStr.string.characters.count
    let searchString = "hi"
    let searchLength = searchString.characters.count
    var range = NSRange(location: 0, length: attrStr.length)
    
    while (range.location != NSNotFound) {
        range = (attrStr.string as NSString).rangeOfString(searchString, options: [], range: range)
        if (range.location != NSNotFound) {
            attrStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.yellowColor(), range: NSRange(location: range.location, length: searchLength))
            range = NSRange(location: range.location + range.length, length: inputLength - (range.location + range.length))
        }
    }