美文网首页
iOS WKWebView侧滑时 html逐级返回

iOS WKWebView侧滑时 html逐级返回

作者: nick5683 | 来源:发表于2022-03-29 14:40 被阅读0次

WKWebView有一个canGoBack属性,该属性为true时表示webview当前加载的html的页面级数 >= 2 ,存在上一级页面,可以返回上一级页面,为false时,表示当前处于html的一级页面,不能返回,侧滑时只能关闭webview。

那么,我们可以通过KVO来监听webview的canGoBack属性值变化来解决html页面的侧滑返回和导航控制器的侧滑返回冲突的问题:即当canGoBack属性值变为true时,禁用导航控制器的侧滑返回手势;当canGoBack的属性值变为false时,解禁导航控制器的侧滑返回手势。

private let canGoBackKeyPath = "canGoBack"

webView.addObserver(self, forKeyPath: canGoBackKeyPath, options: .new, context: nil)

open override func observeValue(forKeyPath keyPath: String?,
                                    of object: Any?,
                                    change: [NSKeyValueChangeKey: Any]?,
                                    context: UnsafeMutableRawPointer?) {
        guard let theKeyPath = keyPath, object as? WKWebView == webView else {
            super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
            return
        }
        if theKeyPath == canGoBackKeyPath{
            if let newValue = change?[NSKeyValueChangeKey.newKey],  let newV = newValue as? Bool{
                 if let edgePan = self.navigationController?.interactivePopGestureRecognizer {
                      edgePan.isEnabled = !newV;
                 }
            }
        }
    }


deinit {
        webView.removeObserver(self, forKeyPath: canGoBackKeyPath, context: nil)
    }

相关文章

网友评论

      本文标题:iOS WKWebView侧滑时 html逐级返回

      本文链接:https://www.haomeiwen.com/subject/hjgvjrtx.html