检测用户是否向左或向右滑动以在WKWebView

时间:2016-05-16 10:36:42

标签: ios webkit wkwebview

我使用的是WKWebView,我允许后退和前进导航手势:

myWkWebView.allowsBackForwardNavigationGestures = true

现在,用户有两种方法可以返回:通过按下按钮或向左滑动。行为会有所不同,所以我想知道我怎么知道用户刚刚向左/向右滑动以便我可以处理它。

我查看了WKNavigationDelegate参考(https://developer.apple.com/library/ios/documentation/WebKit/Reference/WKNavigationDelegate_Ref/),但我找不到任何有用的东西。

有什么想法吗?

修改

我忘了说我还尝试添加滑动手势识别器,这样:

    let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(MyVC.respondToSwipeLeftOrRight(_:)))
    swipeRight.direction = UISwipeGestureRecognizerDirection.Right
    let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(MyVC.respondToSwipeLeftOrRight(_:)))
    swipeLeft.direction = UISwipeGestureRecognizerDirection.Left
    self.view.addGestureRecognizer(swipeRight)
    self.view.addGestureRecognizer(swipeLeft)
    myWkWebView.scrollView.panGestureRecognizer.requireGestureRecognizerToFail(swipeRight)
    myWkWebView.scrollView.panGestureRecognizer.requireGestureRecognizerToFail(swipeLeft)

但每次向左或向右滑动都不会触发它们。

3 个答案:

答案 0 :(得分:2)

sqlite3

答案 1 :(得分:0)

您应该能够使用手势识别器执行此操作,但如果您想在单个视图上处理多个手势识别器,则需要从shouldRecognizeSimultaneouslyWithGestureRecognizer实施UIGestureRecognizerDelegate方法:

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

答案 2 :(得分:0)

看到 SinglePageApplication 无法正常工作,正如 Stefan Rein 所说,我们可以通过检查 Web 视图的手势识别器来合并链接的解决方案。

[self.webView addObserver:self forKeyPath:@"URL" options:NSKeyValueObservingOptionNew context:nil];
//....
- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary<NSKeyValueChangeKey,id> *)change
                       context:(void *)context {
  if ([keyPath isEqualToString:@"URL"]) {    
    for (UIGestureRecognizer *recognizer in self.webView.gestureRecognizers) {
      if ([recognizer isKindOfClass:[UIPanGestureRecognizer class]]) {
        if (((UIPanGestureRecognizer*)recognizer).state == UIGestureRecognizerStateEnded) {
          NSLog(@"Swiped!");
        }
      }
    }
  }
}

当然,如果你有其他手势而不是向前和向后的两个手势,那么你可能需要做更多的检查。