Bold the text that was serched by the user in iOS swift || change particular string color in the textfield in iOS swift
Solution:
The below function will return the attributed string that was searched by the user with background color change. Also you can change the color of the text.
func boldSearchResult(searchString: String, resultString: String) -> NSMutableAttributedString {
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: resultString)
let pattern = searchString.lowercased()
let range: NSRange = NSMakeRange(0, resultString.characters.count)
let regex = try! NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options())
regex.enumerateMatches(in: resultString.lowercased(), options: NSRegularExpression.MatchingOptions(), range: range) { (textCheckingResult, matchingFlags, stop) -> Void in
let subRange = textCheckingResult?.range
attributedString.addAttribute(NSBackgroundColorAttributeName,value: UIColor.yellow, range: subRange!)
}
return attributedString
}
The below function will return the attributed string that was searched by the user with background color change. Also you can change the color of the text.
func boldSearchResult(searchString: String, resultString: String) -> NSMutableAttributedString {
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: resultString)
let pattern = searchString.lowercased()
let range: NSRange = NSMakeRange(0, resultString.characters.count)
let regex = try! NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options())
regex.enumerateMatches(in: resultString.lowercased(), options: NSRegularExpression.MatchingOptions(), range: range) { (textCheckingResult, matchingFlags, stop) -> Void in
let subRange = textCheckingResult?.range
attributedString.addAttribute(NSBackgroundColorAttributeName,value: UIColor.yellow, range: subRange!)
}
return attributedString
}
Comments
Post a Comment