you can use the following function that passes the search input and current content. which will return an NSAttributedString? which you can set in TextView
Swift 3
func generateAttributedString(with searchTerm: String, targetString: String) -> NSAttributedString? { let attributedString = NSMutableAttributedString(string: targetString) do { let regex = try NSRegularExpression(pattern: searchTerm, options: .caseInsensitive) let range = NSRange(location: 0, length: targetString.utf16.count) for match in regex.matches(in: targetString, options: .withTransparentBounds, range: range) { attributedString.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 16, weight: UIFontWeightBold), range: match.range) } return attributedString } catch _ { NSLog("Error creating regular expresion") return nil } }
Edit:
highlight with diacritical insensitive option:
func generateAttributedString(with searchTerm: String, targetString: String) -> NSAttributedString? { let attributedString = NSMutableAttributedString(string: targetString) do { let regex = try NSRegularExpression(pattern: searchTerm.trimmingCharacters(in: .whitespacesAndNewlines).folding(options: .diacriticInsensitive, locale: .current), options: .caseInsensitive) let range = NSRange(location: 0, length: targetString.utf16.count) for match in regex.matches(in: targetString.folding(options: .diacriticInsensitive, locale: .current), options: .withTransparentBounds, range: range) { attributedString.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 16, weight: UIFontWeightBold), range: match.range) } return attributedString } catch { NSLog("Error creating regular expresion: \(error)") return nil } }
source share