swift中让WKWebView中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时,解禁导航控制器的侧滑返回手势。
 

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)
}
 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值