Skip to content

Instantly share code, notes, and snippets.

@xavierjurado
Created May 16, 2018 12:57
Show Gist options
  • Save xavierjurado/2d2c10a9057a9828af39bfffaa68b046 to your computer and use it in GitHub Desktop.
Save xavierjurado/2d2c10a9057a9828af39bfffaa68b046 to your computer and use it in GitHub Desktop.
Adds a link to a URL for a specified text/range
extension NSMutableAttributedString {
/**
Transforms the given text into a tappable link
- parameters:
- url: the destination url
- text: the substring that should be made tappable
- attributes: optional dictionary of parameters to customize the link's appearance
*/
func addLink(to url: URL, from text: String, attributes: [NSAttributedStringKey : Any] = [:]) {
guard let range = string.range(of: text) else {
assertionFailure("Unable to find \(text) inside \(string)")
return
}
addLink(to: url, in: range, attributes: attributes)
}
/**
Transforms the text inside the given range into a tappable link
- parameters:
- url: the destination url
- range: the range of characters that should be made tappable
- attributes: optional dictionary of parameters to customize the link's appearance
*/
func addLink(to url: URL, in range: Range<String.Index>, attributes: [NSAttributedStringKey : Any] = [:]) {
let nsRange = NSRange(range, in: string)
addAttribute(.link, value: url, range: nsRange)
addAttributes(attributes, range: nsRange)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment