I want to highlight all matches word with searching. I wrote code but I couldn\'t use a loop. When i search a word, my app find words and highlight only first word. here is
I want to little improve the solution provided by @Barath and @Bruno Paulino, as this solution won't work with escaped characters like {}[]()'", this solution works with escaped characters, this solution written in SWIFT 5.
func generateAttributedString(with searchTerm: String, targetString: NSAttributedString) -> NSAttributedString? {
let attributedString = NSMutableAttributedString(attributedString: targetString)
do {
let regex = try NSRegularExpression(pattern: NSRegularExpression.escapedPattern(for: searchTerm).trimmingCharacters(in: .whitespacesAndNewlines).folding(options: .regularExpression, locale: .current), options: .caseInsensitive)
let range = NSRange(location: 0, length: targetString.string.utf16.count)
attributedString.addAttribute(NSAttributedString.Key.backgroundColor, value: UIColor.clear, range: range)
for match in regex.matches(in: targetString.string.folding(options: .regularExpression, locale: .current), options: .withTransparentBounds, range: range) {
attributedString.addAttribute(NSAttributedString.Key.backgroundColor, value: UIColor.yellow, range: match.range)
}
return attributedString
} catch {
NSLog("Error creating regular expresion: \(error)")
return nil
}
}