Adding an Activity Indicator (Spinner) to Navigation Bar

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];
  1. Is it necessary to call [activityIndicator stopAnimating] ?

  2. Funny, I implemented exactly this two days ago and wondered about it. Thanks!

  3. To remove the item, shouldn’t it be the RightBarButtonItem, not the LeftBar?

  4. 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?

Comments are closed.