Please consider subscribing to Mobile Developer Tips RSS feed or following us on Twitter
|
|
|
In addition to the standard buttons that you can place on a navigation bar (UINavigationBar), adding an activity indicator (UIActivityIndicator) can be helpful when you need a standard location to indicate some type of action is underway, for example downloading a file, performing a search…
You add an activity indicator through a custom view as shown here:
UIActivityIndicatorView *activityIndicator =
[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
UIBarButtonItem * barButton =
[[UIBarButtonItem alloc] initWithCustomView:activityIndicator];
// Set to Left or Right
[[self navigationItem] setRightBarButtonItem:barButton];
[barButton release];
[activityIndicator startAnimating];
In the code above the reference to self implies this object is a UIViewController. Here is how the spinner will appear in the navbar:

Removing the spinner is as simple as:
[[self navigationItem] setLRightBarButtonItem:nil];
[activityIndicator stopAnimating];
[activityIndicator release];
Related posts:
- Showing Network Activity When there Isn’t Any
- Determining Elapsed Time
- UIAlertView without Buttons – Please Wait Dialog
Comments
6 Responses to “Adding an Activity Indicator (Spinner) to Navigation Bar”
Leave Comment
Is it necessary to call [activityIndicator stopAnimating] ?
[Reply]
John Muchow Reply:
April 26th, 2010 at 7:57 am
Good point Chris, that probably isn’t necessary given it’s released in the next step.
[Reply]
Funny, I implemented exactly this two days ago and wondered about it. Thanks!
[Reply]
To remove the item, shouldn’t it be the RightBarButtonItem, not the LeftBar?
[Reply]
John Muchow Reply:
April 26th, 2010 at 6:30 pm
Good catch on the typo, thanks Kurt, updated.
[Reply]
Great approach John:)
I had been wondering about how to do this without meddling with private API’s in the navigationBar.
I do have both a left and right barButtonItem occupying the space, can it be done in between the buttons, where the Title resides?
[Reply]