我想打印用户手指在网络视图上的位置。
在webview上使用此(如下)不起作用

 override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let position = touch.location(in: self.view) // even when i replace this part with UIWebview
        print(position.x)
        print(position.y)
    }
}

最佳答案

我认为创建UIPanGestureRecognizer应该解决这个问题,在viewDidLoad()方法中添加以下代码:

override func viewDidLoad() {
    // ...

    let panGesture = UIPanGestureRecognizer(target: self, action: #selector(webViewtouchMoved(panGesture:)))
    panGesture.delegate = self

    webView.addGestureRecognizer(panGesture)

    // ...
}

webViewtouchMoved(panGesture:)方法:
func webViewtouchMoved(panGesture: UIPanGestureRecognizer) {
    if panGesture.state == .began || panGesture.state == .changed {
        let position = panGesture.location(in: view)
        print(position.x)
        print(position.y)
    }
}

另外,您应该为所需的ViewController添加这个extension
// change 'ViewController' to your class name:
extension ViewController: UIGestureRecognizerDelegate {
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }
}

希望这有帮助。

07-27 19:40