Swift 4 : XCode 9.x
private func filterAndModifyTextAttributes(searchStringCharacters: String, completeStringWithAttributedText: String) -> NSMutableAttributedString {
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: completeStringWithAttributedText)
let pattern = searchStringCharacters.lowercased()
let range: NSRange = NSMakeRange(0, completeStringWithAttributedText.characters.count)
var regex = NSRegularExpression()
do {
regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options())
regex.enumerateMatches(in: completeStringWithAttributedText.lowercased(), options: NSRegularExpression.MatchingOptions(), range: range) {
(textCheckingResult, matchingFlags, stop) in
let subRange = textCheckingResult?.range
let attributes : [NSAttributedStringKey : Any] = [.font : UIFont.boldSystemFont(ofSize: 17),.foregroundColor: UIColor.red ]
attributedString.addAttributes(attributes, range: subRange!)
}
}catch{
print(error.localizedDescription)
}
return attributedString
}
How to use :
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .subtitle , reuseIdentifier: "Cell")
cell.textLabel?.attributedText = self.filterAndModifyTextAttributes(searchStringCharacters: self.textFromSearchBar, completeStringWithAttributedText: searchResultString)
return cell
}