This code
var textSearch=\"hi\"
var textToShow=\"hi hihi hi\"
var rangeToColor = (textToShow as NSString).rangeOfString(textSearch)
var attributedString =
Using NSRegularExpression saves you from doing all the range calculations on by yourself. This example also will highlight two words instead of just one.
let text = "If you don't have a plan, you become part of somebody else's plan."
let toHighlight = ["plan", "you"]
let range = text.nsRange(from: text.startIndex ..< text.endIndex) // full text
let rangesToHighlight: [[NSRange]] = toHighlight.map { search in
do {
let regex = try NSRegularExpression(pattern: search, options: [])
let matches: [NSTextCheckingResult] = regex.matches(in: text, options: [], range: range)
return matches.map { $0.range } // get range from NSTextCheckingResult
} catch {
return [NSRange]()
}
}
let yellow = UIColor.yellow
let attributedText = NSMutableAttributedString(string: text)
let flattenedRanges: [NSRange] = rangesToHighlight.joined()
flattenedRanges.forEach { // apply color to all ranges
attributedText.addAttribute(NSForegroundColorAttributeName,
value: yellow,
range: $0)
}