Skip to content

Instantly share code, notes, and snippets.

@laevandus
Last active December 14, 2020 13:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save laevandus/5a133953803ff08b16fad716fe493e55 to your computer and use it in GitHub Desktop.
Save laevandus/5a133953803ff08b16fad716fe493e55 to your computer and use it in GitHub Desktop.
private extension HyperlinkLabel {
static func banner(withAlignment alignment: NSTextAlignment, customStyling: Bool, tapHandler: @escaping (URL) -> Void) -> HyperlinkLabel {
let attributedString = NSMutableAttributedString(string: "Check this webpage: %0$@. Link to %1$@ on the App Store. Finally link to %2$@.")
let replacements = [("Augmented Code", URL(string: "https://augmentedcode.io")!),
("SignalPath", URL(string: "https://geo.itunes.apple.com/us/app/signalpath/id1210488485?mt=12")!),
("GitHub", URL(string: "https://github.com/laevandus")!)]
replacements.enumerated().forEach { index, value in
let linkAttribute: NSAttributedString.Key = customStyling ? .hyperlink : .link
let attributes: [NSAttributedString.Key: Any] = [
linkAttribute: value.1
]
let urlAttributedString = NSAttributedString(string: value.0, attributes: attributes)
let range = (attributedString.string as NSString).range(of: "%\(index)$@")
attributedString.replaceCharacters(in: range, with: urlAttributedString)
}
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = alignment
attributedString.addAttribute(.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: attributedString.length))
let label = HyperlinkLabel()
label.attributedText = attributedString
label.translatesAutoresizingMaskIntoConstraints = false
label.didTapOnURL = tapHandler
return label
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment