kwiqsilver
kwiqsilver

Reputation: 1027

Adding an activity indicator to the nav bar

I have a view controller that starts an async network request when the user taps a button, then pushes another controller after the request finishes. In that intervening time, I want the navigation bar to display an activity indicator, so the user knows it's fetching data. I have this code in the IBAction for the button:

self.activityIndicator = [[UIActivityIndicatorView alloc]
     initWithActivityIndicatorStyle: UIActivityIndicatorViewStyleWhite]; 
     // I've tried Gray, White, and WhiteLarge
[self.activityIndicator startAnimating];
self.activityIndicator.hidden = NO;
UIBarButtonItem* spinner = [[UIBarButtonItem alloc] initWithCustomView: self.activityIndicator];
self.navigationItem.rightBarButtonItem = spinner;

The indicator does not appear, but this code is getting called. I've looked at other posts on the topic, and they say to do exactly this. The UI thread does not appear blocked during the call (I can tap other buttons and navigate a different path while waiting). Am I missing something?

Upvotes: 7

Views: 6605

Answers (3)

kwiqsilver
kwiqsilver

Reputation: 1027

I solved it.

There was a cancel button there already that was going away when the keyboard did. The code that removed the cancel button didn't care whether it was removing a button or my spinner. I moved the spinner code to a later location, and all is good.

Upvotes: 2

Alexis
Alexis

Reputation: 16829

You can also try to set the bar button item like this (if you target at least iOS 5):

self.navigationItem.rightBarButtonItems = @[spinner];

Upvotes: 0

willhblackburn
willhblackburn

Reputation: 301

I have had trouble displaying a UIBarButtonItem if one already existed in that place. If this is the case try:

self.navigationItem.rightBarButtonItem = nil;
self.navigationItem.rightBarButtonItem = spinner;

Upvotes: 0

Related Questions