9

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.

Esqarrouth
  • 38,543
  • 21
  • 161
  • 168
  • [This answer](http://stackoverflow.com/a/26495954/1033565) of Benjamin Bojko might help you. – paolo Jun 24 '15 at 21:04
  • 1
    FYI – It's also possible to [create tappable links in UILabel](http://stackoverflow.com/a/29352519/168594). (In case you were only using a UITextView for the data detectors.) – zekel Jun 30 '15 at 21:10

1 Answers1

12

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)
        }
    }
Maroš Beťko
  • 2,181
  • 2
  • 16
  • 42
Thellimist
  • 3,757
  • 5
  • 31
  • 49
  • Couldn't use key `NSLinkAttributeName` in Swift 4. A simple workaround is to use key `"NSLink"` instead. – Legonaftik Nov 30 '17 at 08:39
  • Thanks a lot. I could not use shouldInteractWithURL, it conflicted with my gesture recognizer (I could not cancel gesture action if link is clicked). So I did it in gesture recognizer as in your answer – samir105 Dec 07 '20 at 07:28