Skip to content

Instantly share code, notes, and snippets.

@laevandus

laevandus/HyperlinkLabel.swift Secret

Created Dec 15, 2020
Embed
What would you like to do?
override var attributedText: NSAttributedString? {
get {
return super.attributedText
}
set {
super.attributedText = {
guard let newValue = newValue else { return nil }
// Apply custom hyperlink attributes
let text = NSMutableAttributedString(attributedString: newValue)
text.enumerateAttribute(.hyperlink, in: NSRange(location: 0, length: text.length), options: .longestEffectiveRangeNotRequired) { (value, subrange, _) in
guard let value = value else { return }
assert(value is URL)
text.addAttributes(hyperlinkAttributes, range: subrange)
}
// Fill in font attributes when not set
text.enumerateAttribute(.font, in: NSRange(location: 0, length: text.length), options: .longestEffectiveRangeNotRequired) { (value, subrange, _) in
guard value == nil, let font = font else { return }
text.addAttribute(.font, value: font, range: subrange)
}
return text
}()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment