Created
February 18, 2019 09:58
-
-
Save nil-biribiri/5e5970c31cdf8adebc0b9872f8eb5480 to your computer and use it in GitHub Desktop.
UITextView extension for clickable hyperlink.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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