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
Improved customized solution for Swift 4.2
extension NSAttributedString {
convenience init(base: String,
keyWords: [String],
foregroundColor: UIColor,
font: UIFont,
highlightForeground: UIColor,
highlighBackground: UIColor) {
let baseAttributed = NSMutableAttributedString(string: base, attributes: [NSAttributedString.Key.font: font,
NSAttributedString.Key.foregroundColor: foregroundColor])
let range = NSRange(location: 0, length: base.utf16.count)
for word in keyWords {
guard let regex = try? NSRegularExpression(pattern: word, options: .caseInsensitive) else {
continue
}
regex
.matches(in: base, options: .withTransparentBounds, range: range)
.forEach { baseAttributed
.addAttributes([NSAttributedString.Key.backgroundColor: highlighBackground,
NSAttributedString.Key.foregroundColor: highlightForeground],
range: $0.range) }
}
self.init(attributedString: baseAttributed)
}
}