直接上代码吧
import UIKit
import WebKit
class ShareWebViewController: UIViewController,WKUIDelegate, WKNavigationDelegate,UIWebViewDelegate {
var index = 0
var urlArr = NSArray()
var titleArr = NSArray()
var webView:WKWebView?
lazy private var progressView: UIProgressView = {
self.progressView = UIProgressView.init(frame: CGRect(x: CGFloat(0), y: CGFloat(1), width: UIScreen.main.bounds.width, height: 2))
self.progressView.tintColor = UIColor.green // 进度条颜色
self.progressView.trackTintColor = UIColor.white // 进度条背景色
return self.progressView
}()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.barTintColor = UIColor.white
setUpWKwebView()
}
// 创建webview
func setUpWKwebView() {
let model = urlArr[index] as! advDataModel
let webview = WKWebView(frame: CGRect.init(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT-64))
let url = NSURL(string: model.url ?? "")
let request = NSURLRequest.init(url: url! as URL)
webview.load(request as URLRequest)
self.view.addSubview(webview)
self.view.addSubview(progressView)
self.webView = webview
self.webView?.uiDelegate = self
self.webView?.navigationDelegate = self
self.title = model.name
self.webView?.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
// 加载进度条
if keyPath == "estimatedProgress"{
progressView.alpha = 1.0
progressView.setProgress(Float((self.webView?.estimatedProgress) ?? 0), animated: true)
if (self.webView?.estimatedProgress ?? 0.0) >= 1.0 {
UIView.animate(withDuration: 0.3, delay: 0.1, options: .curveEaseOut, animations: {
self.progressView.alpha = 0
}, completion: { (finish) in
self.progressView.setProgress(0.0, animated: false)
})
}
}
}
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!){
}
func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!){
MBProgressHUD.hideAllHUDs(for: self.view, animated: true)
}
func webViewDidClose(_ webView: WKWebView) {
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
}
deinit {
self.webView?.removeObserver(self, forKeyPath: "estimatedProgress")
self.webView?.uiDelegate = nil
self.webView?.navigationDelegate = nil
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}