標籤:沒有 span dispatch nim sel hidden idf tco nil
導航:
1.載入進度條
2.導覽列增加返回、關閉按鈕
載入進度條
代碼如下:
self.progressView.trackTintColor = UIColor.whiteself.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 KVOself.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)