Last active
May 31, 2023 13:59
-
-
Save cedricbahirwe/3075d92a075c1e874aa17086094b6fb8 to your computer and use it in GitHub Desktop.
This file contains 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 String { | |
func add(highlight: String, color: UIColor = .white) -> NSAttributedString { | |
let attributedString = NSMutableAttributedString(string: self) | |
guard | |
let range = self.range(of: highlight), | |
let fullRange = self.range(of: self) | |
else { | |
return attributedString | |
} | |
let nsFullRange = NSMakeRange(fullRange.lowerBound.utf16Offset(in: self), self.count) | |
attributedString.addAttributes([.foregroundColor: color], | |
range: nsFullRange) | |
let nsRange = NSMakeRange(range.lowerBound.utf16Offset(in: self), highlight.count) | |
attributedString.addAttributes([.foregroundColor: color, | |
.underlineColor: color, | |
.link: "https://www.google.com", | |
.underlineStyle: NSUnderlineStyle.single.rawValue], | |
range: nsRange) | |
return attributedString | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment