August 24, 2016 - No Comments!

Highlight instances of string in NSMutableAttributedString

This is just a small feature I implemented into a recent project but could be very useful. It will highlight instances of a string within a NSMutableAttributedString.

For example - a we could highlight each instance of "we" in "We all went to the beach on Wednesday". In practice I added this to a search suggestion field to show where the matches were taking place.

import UIKit

extension NSMutableAttributedString {

func highlightInstancesOfString(string: String, color: UIColor) -> NSMutableAttributedString {
let regPattern = string.lowercaseString
if let regex = try? NSRegularExpression(pattern: regPattern, options: []) {
let matchesArray = regex.matchesInString(self.string.lowercaseString, options: [], range: NSRange(location: 0, length: self.length))
for match in matchesArray {
self.addAttribute(NSForegroundColorAttributeName, value: color, range: match.range)
}
}
return self
}
}

In use

let string = NSMutableAttributedString(string: "We all went to the beach on Wednesday")
label.attributedText = string.highlightInstancesOfString("we", color: UIColor.redColor())

Leave a Reply