Search code examples
iosswiftuiwebviewuitextviewdatadetectortypes

UITextView open link on tap


I use this code:

var textView = UITextView(x: 10, y: 10, width: CardWidth - 20, height: placeholderHeight) //This is my custom initializer
textView.text = "dsfadsaf www.google.com"
textView.selectable = true
textView.dataDetectorTypes = UIDataDetectorTypes.Link
textView.delegate = self
addSubview(textView)

The problem is the link needs long tap gesture to open. I want it to open with a single tap, just like in the Facebook app.


Solution

  • The example below only works on iOS 8+

    Tap 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 force unwraps:

    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)
            }
        }