Created
June 27, 2019 07:58
-
-
Save lamprosg/874c05e400a00142e3d8a1d6cf533bf8 to your computer and use it in GitHub Desktop.
(iOS) Label string highlight
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
| import UIKit | |
| extension UILabel { | |
| /// Highlights a specific substring of the label's text with a desired color | |
| /// Text must be set before calling this method. | |
| /// | |
| /// - Parameters: | |
| /// - subString: The substring to change color | |
| /// - color: The desired color | |
| func highlight(subString: String, color: UIColor?) { | |
| guard let text = self.text, | |
| let color = color else { | |
| return | |
| } | |
| let attributedString = NSMutableAttributedString(string: text) | |
| let option = NSString.CompareOptions.caseInsensitive | |
| let range = attributedString.mutableString.range(of: subString, | |
| options: option) | |
| if range.location != NSNotFound { | |
| attributedString.beginEditing() | |
| attributedString.addAttribute(NSAttributedString.Key.foregroundColor, | |
| value: color, | |
| range: range) | |
| attributedString.endEditing() | |
| self.attributedText = attributedString | |
| } | |
| self.layoutIfNeeded() | |
| } | |
| /// Resets the highlighting to the previous font style | |
| func resetHighlighting() { | |
| guard let text = self.text, | |
| let textColor = self.fontColor else { | |
| return | |
| } | |
| let attributedString = NSMutableAttributedString(string: text) | |
| let option = NSString.CompareOptions.caseInsensitive | |
| let range = attributedString.mutableString.range(of: text, | |
| options: option) | |
| if range.location != NSNotFound { | |
| attributedString.beginEditing() | |
| attributedString.addAttribute(NSAttributedString.Key.foregroundColor, | |
| value: textColor, | |
| range: range) | |
| attributedString.endEditing() | |
| self.attributedText = attributedString | |
| } | |
| self.layoutIfNeeded() | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment