Skip to content

Instantly share code, notes, and snippets.

@mlabraca
Last active January 12, 2017 15:24
Show Gist options
  • Save mlabraca/162d0fc08a135a09af509890f4aa9643 to your computer and use it in GitHub Desktop.
Save mlabraca/162d0fc08a135a09af509890f4aa9643 to your computer and use it in GitHub Desktop.
UILabel extension to highlight specified text
extension UILabel {
func highlight(searchText: String, color: UIColor = .yellow) {
guard let labelText = self.text else { return }
do {
let mutableString = NSMutableAttributedString(string: labelText)
let regex = try NSRegularExpression(pattern: searchText, options: .caseInsensitive)
for match in regex.matches(in: labelText, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSRange(location: 0, length: labelText.utf16.count)) as [NSTextCheckingResult] {
mutableString.addAttribute(NSBackgroundColorAttributeName, value: color, range: match.range)
}
self.attributedText = mutableString
} catch {
print(error)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment