Last active
January 12, 2017 15:24
-
-
Save mlabraca/162d0fc08a135a09af509890f4aa9643 to your computer and use it in GitHub Desktop.
UILabel extension to highlight specified text
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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