Skip to content

Instantly share code, notes, and snippets.

@cedricbahirwe
Last active May 31, 2023 13:59
Show Gist options
  • Save cedricbahirwe/3075d92a075c1e874aa17086094b6fb8 to your computer and use it in GitHub Desktop.
Save cedricbahirwe/3075d92a075c1e874aa17086094b6fb8 to your computer and use it in GitHub Desktop.
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