Skip to content

Instantly share code, notes, and snippets.

@nil-biribiri
Created February 18, 2019 09:58
Show Gist options
  • Save nil-biribiri/5e5970c31cdf8adebc0b9872f8eb5480 to your computer and use it in GitHub Desktop.
Save nil-biribiri/5e5970c31cdf8adebc0b9872f8eb5480 to your computer and use it in GitHub Desktop.
UITextView extension for clickable hyperlink.
extension UITextView {
func hyperLink(originalText: String,
hyperLink: String,
urlString: String,
withFont font: UIFont = UIFont.systemFont(ofSize: 16.0),
textColor: UIColor = .black,
linkColor: UIColor = .blue) {
isEditable = false
let style = NSMutableParagraphStyle()
style.alignment = .left
let attributedOriginalText = NSMutableAttributedString(string: originalText)
let linkRange = attributedOriginalText.mutableString.range(of: hyperLink)
let fullRange = NSMakeRange(0, attributedOriginalText.length)
attributedOriginalText.addAttribute(NSAttributedString.Key.link, value: urlString, range: linkRange)
attributedOriginalText.addAttribute(NSAttributedString.Key.paragraphStyle, value: style, range: fullRange)
attributedOriginalText.addAttribute(NSAttributedString.Key.foregroundColor, value: textColor, range: fullRange)
attributedOriginalText.addAttribute(NSAttributedString.Key.font, value: font, range: fullRange)
self.linkTextAttributes = [
NSAttributedString.Key.foregroundColor.rawValue: linkColor,
NSAttributedString.Key.underlineStyle: NSUnderlineStyle.styleSingle.rawValue,
] as? [String: Any]
self.attributedText = attributedOriginalText
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment