继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

iOS 如何让WKWebView侧滑返回时html逐级返回,而不是直接返回到上级控制器?

慕森王
关注TA
已关注
手记 264
粉丝 107
获赞 549

iOS使用WKWebView来加载html页面时,如果html页面只有一级的话,那么侧滑返回没什么问题,但如果html是多级的话,那么侧滑返回时有时就会出现直接返回到上级控制器,而不是返回上一级html页面。这是因为html页面的侧滑返回和导航控制器的侧滑返回发生冲突了,系统无法识别到底是哪一种侧滑返回。

WKWebView有一个canGoBack属性(A Boolean value indicating whether there is a back item in the back-forward list that can be navigated to.),该属性为true/YES时表示webview当前加载的html的页面级数 >= 2 ,为false/NO时,表示当前处于html的一级页面。

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

具体操作如下:

Swift版:

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 newV == true{
                    self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false;
                }else{
                    self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true;
                }
            }
        }
    }


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

OC版:

懒得写了,自己照着Swift版的转换一下吧~

原文出处

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP