This will be a very short and simple tutorial demonstrating how to use a UIActivityIndicatorView to let a user know that something is taking place in your app.
1.) Create a new Navigation-based Application and name it ActivityTutorial.
2.) Open up RootViewController.h and add a UIActivityIndicatorView declaration.
3.) Open up RootViewController.m and implement the activityIndicator in the viewDidLoad method.
4.) Start the activityIndicator animating in the viewWillAppear method.
5.) Set the number of rows for our table view to be 1.
6.) Set the text for our one row to be “Stop Animation”. We do this in the tableView:cellForRowAtIndexPath:indexPath method. For more information on how to set up a tableView see the UITableView tutorials.
7.) Find the tableView:didSelectRowAtIndexPath:indexPath method. We are going to add the line of code to stop the animation here.
So what’s happening is the animation starts with the code we added in the viewWillAppear method and then stops when you click the row in the table view.
This isn’t exactly a real world example. I mean we’re not going to have an activity indicator going until a user stops it. But it should be a good enough example for you to implement it in your own code. Just find the spot where an activity begins and start the animation, then you will somehow need to be notified when the activity ends and stop the animation.
As an example in the app I’m currently working on there is a fairly complex database query that takes a few seconds to return the results and load them into the table view. I start the animation in the viewWillAppear method. Then in my methods that retrieve the data from the database I have a reload statement that reloads the table view and immediately after that I stop the animation.
8.) Let’s take this a step further, just for fun. Go back to the tableView:numberOfRowsInSection:section method and set our number of rows to 2.
9.) Now change the tableView:cellForRowAtIndexPath:indexPath method to set text in two rows.
10.) And then change the tableView:didSelectRowAtIndexPath:indexPath method to handle both rows. The first row will stop the animation, and the second row will start the animation.
There you go, that’s all there is to it. Save everything and click Build and Run and see what we’ve got.