Get actual coordinate of pdf in Webview when touch with Swift 3

亡梦爱人 提交于 2019-12-23 05:42:10

问题


I have successfully to load a pdf file from URL to a web view. I want to get the coordinates after touch on webview to sent it data to server to add some text to that position in server side. Problem is how can I get that coordinates when webview is zooming or scroll to page 2,3.. Could you please help me to solve the problem in Swift 3

Here the code

class ViewController: UIViewController, UITextFieldDelegate, UIGestureRecognizerDelegate, UIWebViewDelegate {

    @IBOutlet var imageView: UIImageView!
    @IBOutlet var webView: UIWebView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let url = URL(string: "http://www.pdf995.com/samples/pdf.pdf")!
        webView.loadRequest(URLRequest(url: url))

        let webViewTapped = UITapGestureRecognizer(target: self, action: #selector(self.tapAction(_:)))
        webViewTapped.numberOfTouchesRequired = 1
        webViewTapped.delegate = self
        webView.addGestureRecognizer(webViewTapped)
    }

    func tapAction(_ sender: UITapGestureRecognizer) {
        // This always return the same coordinates in zoom or not zoom
        let point = sender.location(in: webView)
        print("======")
        print("x: \(point.x) y: \(point.y)")
    }

PS: I am a newbie in swift


回答1:


user3783161,

First of all, you can remove the following line, if you don't use any method from UIGestureRecognizerDelegate. webViewTapped.delegate = self

To get the the actual coordinate when you touch the UIWebView, you need to get the location on UIScrollView and not from UIWebView.

func tapAction(_ sender: UITapGestureRecognizer) {
    // This always return the same coordinates in zoom or not zoom
    // let point = sender.location(in: webView)
    // print("======WebView")
    // print("x: \(point.x) y: \(point.y)")

    // Get location frown webView.ScrollView
    let point = sender.location(in: webView.scrollView)
    print("======ScrollView")
    print("x: \(point.x) y: \(point.y)")
}

But you still have a problem, because the location is relative to the content size of the UIWebView and not to the PDF document. I did not find the answer to this, but you can do a simple conversion between:

PDF Paper Size vs. WebView Size

Since the PDF must have this information (the pdf can be A4 / A3 / A5 / C1 / etc).



来源:https://stackoverflow.com/questions/45072786/get-actual-coordinate-of-pdf-in-webview-when-touch-with-swift-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!