WKWebview allowBackForwardNavigationGestures和UINavigationController interactivePopGestureRecognizer都启用

时间:2016-07-21 09:29:53

标签: ios uinavigationcontroller wkwebview

嵌入在导航控制器中的My View Controller包含一个WKWebview,我想在其上启用以下逻辑:

如果webview中存在后退项目,则进行左侧屏幕边缘手势应返回webview中的一个页面(当allowBackForwardNavigationGestures设置为yes时,webview的正常行为)。如果没有任何后退项目,它应该在导航控制器中弹出一个页面(interactivePopGestureRecognizer)。我启用了两个并获得随机结果,有时我会在webview中返回一页,有时我会回到导航堆栈中的主页。我尝试了以下逻辑:

-(void)webView:(WKWebView *)webView didCommitNavigation:(null_unspecified WKNavigation *)navigation {

  if (webView.backForwardList.backItem) {
    MYappDelegate.mainNavigationController.interactivePopGestureRecognizer.enabled = NO;
    self.webView.allowsBackForwardNavigationGestures = YES;
  } else {
    MYappDelegate.mainNavigationController.interactivePopGestureRecognizer.enabled = YES;
    self.webView.allowsBackForwardNavigationGestures = NO;
  }
}

但是当我滑动时它会崩溃并且我将“WKCompositingView无法识别的选择器发送到实例。”

我出错的任何想法?我猜是关于哪个手势占优先权存在冲突,但是我无法弄清楚在哪里添加这个逻辑,因此webview和包含其视图控制器的导航控制器都能和平地生活。

3 个答案:

答案 0 :(得分:2)

我有同样的问题。请尝试以下方式:

首先,向WebView添加自定义手势:

    let swipe = UISwipeGestureRecognizer(target: self, action: #selector(goBack))
    swipe.direction = UISwipeGestureRecognizerDirection.right
    swipe.delegate = self.navigationController
    webView.addGestureRecognizer(swipe)

然后,添加一个UIGestureDelegate方法来同时处理手势,

extension UINavigationController: UIGestureRecognizerDelegate{
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRequireFailureOf otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return gestureRecognizer is UIScreenEdgePanGestureRecognizer
}

public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return true
}

}

但它有一个小缺陷,即滑动效果与原生效果不同,后者在没有触摸的情况下滑动时会显示新的viewController。

答案 1 :(得分:1)

_webView.allowsBackForwardNavigationGestures = YES;

-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    self.navigationController.interactivePopGestureRecognizer.enabled = _webView.canGoBack ? NO : YES;
}

答案 2 :(得分:0)

也许你可以使用canGoback的观察者,比如

padding: calc(*put fixed pixels here*px + *put your required %age here*%) 

如果值为true,请执行

RACObserve(self.wk_webView, canGoBack)