Floyd Resler Floyd Resler - 4 months ago 36
Swift Question

iOS Swift UIWebView Link Coordinates

I need to get the coordinates of a link tapped on in a UIWebView. I tried using TapGestureRecognizer but it doesn't trigger when the link is tapped. I thought I might be able to get the coordinates from Javascript via stringByEvaluatingJavaScriptFromString and I couldn't get that to work either. How can I accomplish this?

Answer

A Swift equivalent of this answer: How to detect touch on UIWebView.

import UIKit

class ViewController: UIViewController, UIGestureRecognizerDelegate {

    let myWebView = UIWebView()

    override func viewDidLoad() {
        super.viewDidLoad()

        myWebView.frame = self.view.frame
        self.view.addSubview(myWebView)
        myWebView.loadRequest(NSURLRequest(URL: NSURL(string: "https://stackoverflow.com")!))

        let webViewTapped = UITapGestureRecognizer(target: self, action: "tapAction:")
        webViewTapped.numberOfTouchesRequired = 1
        webViewTapped.delegate = self
        myWebView.addGestureRecognizer(webViewTapped)
    }

    func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }

    func tapAction(sender: UIGestureRecognizer) {
        let point = sender.locationInView(self.view)
        println(point.x)
        println(point.y)
    }
Comments