如何让UIA活动指标一旦出现就消失



我目前在打开应用程序时将我的应用程序链接到某个 URL,这显然会在打开它和实际加载 webView 之间有延迟,所以我希望它在 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()
}

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

组织代码的方式有点令人困惑。 您似乎正在@IBAction函数声明您的func。 如果是这种情况,这将不起作用。

试试这个

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()
}

最新更新