Creating programmatically a spinner (UIActivityIndicator)

May 8th, 2009 by Chris Leave a reply »

UIActivityIndicator commonly named Spinner is used usually to tell the user that some process is currently in progress.

There are three types of UIActivityIndicators:

activityindicators From the left: gray (UIActivityIndicatorViewStyleGray), white (UIActivityIndicatorViewStyleWhite) and large white (UIActivityIndicatorViewStyleWhiteLarge).

To allocate any of them use the following code:

	UIActivityIndicatorView *myIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge]];
	myIndicator.center = CGPointMake(160, 240);
	myIndicator.hidesWhenStopped = NO;

As you see this time you shouldn’t provide initWithFrame as long as large white style has got different dimensions then white (small) and gray. Instead, set its center point.

To add UIActivityIndicator to your view simple use addSubview method:

	[self.view addSubview:myIndicator];

By default, UIActivityIndicator displays a static image, what in most cases isn’t what you want. You can easily start and stop animating it by using two methods:

	[myIndicator startAnimating];
	[myIndicator stopAnimating]; 

Please note: the hidesWhenStopped=YES property causes the UIActivityIndicator disappear once you stopped animating it and appear again once you started animating.

If you need to know programatically what is the current state of UIActivityIndicator, you can use isAnimating property:

if ([myIndicator isAnimating]) NSLog(@"animating");
else NSLog(@"not animating");

UIActivityIndicator in status bar

spinnerstatusbarTo display a UIActivityIndicator use the UIApplication’s property: networkActivityIndicatorVisible.

	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

and to disable:

	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

That’s almost all about UIActivityIndicator. More can be found in UIActivityIndicator Class Reference in documentation.

Advertisement

1 comment

  1. Chris says:

    Great article. It was very easy to follow and had me up and running in no time.

    There is one small error in your code though:

    UIActivityIndicatorView *myIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge]];

    should be

    UIActivityIndicatorView *myIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];

    There is an extra “]” at the end of your example.

    Thanks again for the great article.

Leave a Reply