设为首页收藏本站

安徽论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 50619|回复: 0

iOS 让WKWebView侧滑返回时html逐级返回

[复制链接]

1

主题

0

回帖

3

积分

新手上路

Rank: 1

积分
3
发表于 2022-2-2 11:58:18 | 显示全部楼层 |阅读模式
网站内容均来自网络,本站只提供信息平台,如有侵权请联系删除,谢谢!
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方法代码转换
或使用以下方式达到想要效果
pod 'TDWebViewSwipeBack'
只需要一句代码
[self addWkwebView:self.wkWebView swipeBackAble:YES];demo演示
https://github.com/strivever/TDWebViewSwipeBack

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
免责声明
1. 本论坛所提供的信息均来自网络,本网站只提供平台服务,所有账号发表的言论与本网站无关。
2. 其他单位或个人在使用、转载或引用本文时,必须事先获得该帖子作者和本人的同意。
3. 本帖部分内容转载自其他媒体,但并不代表本人赞同其观点和对其真实性负责。
4. 如有侵权,请立即联系,本网站将及时删除相关内容。
懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表