Using UIActivityIndicatorView with UIWebView in Swift

无人久伴 提交于 2019-12-03 11:49:24

First of all, i don't see delegation of UIWebView. Realize your behaviour related to delegation processes.

UIWebViewDelegate has four methods, but use for this way just three:

Swift 4

func webViewDidStartLoad(_ webView: UIWebView) // show indicator    
func webViewDidFinishLoad(_ webView: UIWebView) // hide indicator
func webView(_ webView: UIWebView, didFailLoadWithError error: Error) // hide indicator

Swift 3

func webViewDidStartLoad(webView: UIWebView!) // show indicator
func webViewDidFinishLoad(webView: UIWebView!) // hide indicator
func webView(webView: UIWebView!, didFailLoadWithError error: NSError!) // hide indicator

You need to add UIWebViewDelegate to your class like so.

class HighchartsController: UIViewController, UIWebViewDelegate {

You will also need to assign your webView delegate to self in viewDidLoad function like so.

HighchartsView.delegate = self

*WKWebView equivalent of dimpiax answer. Use WKNavigationDelegate

func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) // show indicator 

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!)  // hide indicator 

func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error)  // hide indicator*  

I'm sure you figured it out by now but you need to wire up your UIWebView to set its delegate as your UIViewController in the storyboard by control-dragging.

The following are three simple steps that I always follow in Xcode 8 / Swift 3 / iOS 10 in order to implement UIWebView page loading indicator:

Step 1. Create outlets for the Web View and Load Indicator in the ViewController class. For example:

@IBOutlet var loadSpinner: UIActivityIndicatorView!
@IBOutlet weak var webView: UIWebView!

These two lines should have non-empty dots to the left of them.

Step 2. In the Storyboard: Control-drag the WebView to the ViewController and choose "delegate" from the menu. As GarySabo correctly pointed out, without this step, the indicator will appear but won't work!

Step 3. Add the following code to your ViewController class:

func webViewDidStartLoad(_ : UIWebView) {
    loadSpinner.startAnimating()
}

func webViewDidFinishLoad(_ : UIWebView) {
    loadSpinner.stopAnimating()
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!