The example below only works on iOS 8+
Click Recognizer:
let tapRecognizer = UITapGestureRecognizer(target: self, action: Selector("tappedTextView:")) myTextView.addGestureRecognizer(tapRecognizer) myTextView.selectable = true
Callback:
func tappedTextView(tapGesture: UIGestureRecognizer) { let textView = tapGesture.view as! UITextView let tapLocation = tapGesture.locationInView(textView) let textPosition = textView.closestPositionToPoint(tapLocation) let attr: NSDictionary = textView.textStylingAtPosition(textPosition, inDirection: UITextStorageDirection.Forward) if let url: NSURL = attr[NSLinkAttributeName] as? NSURL { UIApplication.sharedApplication().openURL(url) } }
Swift 3 and no showdown:
func tappedTextView(tapGesture: UIGestureRecognizer) { guard let textView = tapGesture.view as? UITextView else { return } guard let position = textView.closestPosition(to: tapGesture.location(in: textView)) else { return } if let url = textView.textStyling(at: position, in: .forward)?[NSLinkAttributeName] as? URL { UIApplication.shared.open(url) } }
source share