如何让 UIActivityIndi​​cator 一旦出现就消失?

How to get UIActivityIndicator to disappear once appearing?

我目前有我的应用程序在打开应用程序时链接到某个 URL,这显然在打开它和实际加载 webView 之间会有延迟,所以我希望它显示一个 activity 指示符,每当加载 webView 时,我的 ViewController.swift 中都有以下代码:

class ViewController: UIViewController, UIWebViewDelegate {


@IBOutlet weak var webView: UIWebView!  

@IBOutlet weak var activityIndicator: UIActivityIndicatorView!

override func viewDidLoad() {
    super.viewDidLoad()

    webView.delegate = self

    let url = URL(string: "url to site")
    webView.loadRequest(URLRequest(url: url!)
}

func webViewDidStartLoad(webView: UIWebView){
    activityIndicator.startAnimating()
}

func webViewDidFinishLoad(webView: UIWebView){
    activityIndicator.stopAnimating()
}

activity 指示器从一开始就显示,但一旦 webView 加载并永远保持不变,它就不会消失。

您组织代码的方式有点混乱。看来您是在 func 内部 中声明 @IBAction 函数。如果是这种情况,这将不起作用。

试试这个

class ViewController: UIViewController, UIWebviewDelegate {
    override func viewDidLoad() {
        ...
        webView.delegate = self

        // You should add this to your Storyboard, above the webview instead of here in the code 
        activityIndicator.center = self.view.center
        activityIndicator.hidesWhenStopped = true
        activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray
        // I forget the actual method name - look it up
        view.insertSubview(activityIndicator, above: webView)
    }

    @IBAction func openButton(_ sender: Any) { 
        let url = URL(string: "websiteURL")
        webView.loadRequest(URLRequest(url: url!))
    }

    func webViewDidStartLoad(webView: UIWebView){
        activityIndicator.startAnimating()
    }

    func webViewDidFinishLoad(webView: UIWebView){
        activityIndicator.stopAnimating()
    } 

    // You'll also want to add the "didFail" method
}

问题是语法问题,你必须在函数中添加下划线。

override func viewDidLoad() {
    super.viewDidLoad()

    webView.delegate = self

    let url = URL(string: "your URL")
    webView.loadRequest(URLRequest(url: url!))
}

func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool{

    activityIndicator.startAnimating()
    return true
}

func webViewDidStartLoad(_ webView: UIWebView){

    activityIndicator.startAnimating()
}

func webViewDidFinishLoad(_ webView: UIWebView){

    activityIndicator.stopAnimating()
}

func webView(_ webView: UIWebView, didFailLoadWithError error: Error){

    activityIndicator.stopAnimating()
}