iOS WKWebView 加载进度条导航栏返回&关闭 (Swift 4)
Posted Ficow Shen
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iOS WKWebView 加载进度条导航栏返回&关闭 (Swift 4)相关的知识,希望对你有一定的参考价值。
导航:
1.加载进度条
效果图
代码如下:
self.progressView.trackTintColor = UIColor.white self.progressView.progressTintColor = UIColor.colorWithHex(value: 0x72A438, alpha: 1).withAlphaComponent(0.8) self.progressView.frame = CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 1) self.progressView.transform = CGAffineTransform.init(scaleX: 1, y: 3) self.view.addSubview(self.progressView) self.progressView.progress = 0.05 //设置初始值,防止网页加载过慢时没有进度 // Swift 4 KVO self.observeBlock = webView.observe(\\.estimatedProgress, options: NSKeyValueObservingOptions.new.union(NSKeyValueObservingOptions.old)) { (webview, changed) in if let new = changed.newValue{ self.progressView.isHidden = false self.progressView.progress = Float(new) if new >= 1.0{ delay(second: 0.3, block: { self.progressView.isHidden = true }) } } }
// 加载失败隐藏进度条 func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { self.progressView.isHidden = true }
延迟执行函数:
func delay(second:Double,block:@escaping (() -> Void)){ DispatchQueue.main.asyncAfter(deadline: .now() + second, execute: { block() }) }
效果图
代码如下:
func showLeftNavigationItem(){ let goBackBtn = UIButton.init() let closeBtn = UIButton.init() goBackBtn.setImage(UIImage.init(named: "navi_go_back"), for: UIControlState.normal) goBackBtn.setTitle(" 返回", for: UIControlState.normal) goBackBtn.addTarget(self, action: #selector(goBack), for: UIControlEvents.touchUpInside) goBackBtn.sizeToFit() goBackBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -8, 0, 8) let backItem = UIBarButtonItem.init(customView: goBackBtn) closeBtn.setTitle("关闭", for: UIControlState.normal) closeBtn.addTarget(self, action: #selector(popViewController), for: UIControlEvents.touchUpInside) closeBtn.sizeToFit() let closeItem = UIBarButtonItem.init(customView: closeBtn) let items:[UIBarButtonItem] = [backItem,closeItem] self.navigationItem.leftBarButtonItems = items }
按钮对应的Selector:
@objc func goBack(){ self.webView.goBack() } @objc func popViewController(){ self.navigationController?.popViewController(animated: true) }
加载完成时,决定是否显示这两个按钮:
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { checkGoBack() } func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { checkGoBack() } /// 检查返回(pop/goback) func checkGoBack(){ self.navigationController?.interactivePopGestureRecognizer?.isEnabled = !self.webView.canGoBack if self.webView.canGoBack{ showLeftNavigationItem() }else{ self.navigationItem.leftBarButtonItems = nil } }
白色返回箭头图片:
右键括号处保存 2x:() 3x:()
Ficow原创,转载请注明出处:http://www.cnblogs.com/ficow/p/7639912.html
以上是关于iOS WKWebView 加载进度条导航栏返回&关闭 (Swift 4)的主要内容,如果未能解决你的问题,请参考以下文章
iOS WKWebView与H5交互,JS调OC传值、OC调JS传值、进度条加载等(干货满满)