How to show activity indicator while tableView loads?

Orkhan Alizade picture Orkhan Alizade · Apr 28, 2015 · Viewed 54.5k times · Source

When I switch between my tabs it loads some seconds and I want to know that my data is loading. For that I decided to add an activity indicator.

I wrote a little function:

func showActivityIndicator() {
    dispatch_async(dispatch_get_main_queue()) {
        self.spinner = UIActivityIndicatorView(activityIndicatorStyle: .WhiteLarge)
        self.spinner.frame = CGRect(x: 0.0, y: 0.0, width: 80.0, height: 80.0)
        self.spinner.center = CGPoint(x:self.loadingView.bounds.size.width / 2, y:self.loadingView.bounds.size.height / 2)

        self.loadingView.addSubview(self.spinner)
        self.view.addSubview(self.loadingView)
        self.spinner.startAnimating()
    }
}

that will show my indicator. And try to use it when I tapped from my infoController to button:

@IBAction func goToMainFromInfo(sender: AnyObject) {
        self.showActivityIndicator()
        self.performSegueWithIdentifier("fromMainToInfoWActivity", sender: nil)
        self.hideActivityIndicator()
    }
}

I show it before segue perform and hide after. It doesn't help me. When I did try to use sync:

@IBAction func goToMainFromInfo(sender: AnyObject) {
    dispatch_async(dispatch_get_main_queue()) {
        self.showActivityIndicator()
        self.performSegueWithIdentifier("fromMainToInfoWActivity", sender: nil)
        self.hideActivityIndicator()
    }
}

But it doesn't help too. When I press to tab it opacity becomes 0.5 and I wait while it loading. But I do not see my activity indicator.

What is the problem?

Answer

Lydia picture Lydia · Apr 28, 2015

Just try this:

var indicator = UIActivityIndicatorView()

func activityIndicator() {
    indicator = UIActivityIndicatorView(frame: CGRectMake(0, 0, 40, 40))
    indicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
    indicator.center = self.view.center
    self.view.addSubview(indicator)    
}

And where you want to start animating

indicator.startAnimating()
indicator.backgroundColor = UIColor.whiteColor()

For stop:

indicator.stopAnimating()
indicator.hidesWhenStopped = true

Note: Avoid the calling of start and stop at the same time. Just give some conditions.

SWIFT : 4.2 Just try this:

var indicator = UIActivityIndicatorView()

func activityIndicator() {
    indicator = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
    indicator.style = UIActivityIndicatorView.Style.gray
    indicator.center = self.view.center
    self.view.addSubview(indicator)   
}

And where you want to start animating

activityIndicator()
indicator.startAnimating()
indicator.backgroundColor = .white

For stop:

indicator.stopAnimating()
indicator.hidesWhenStopped = true