Adding an Activity Indicator with UIActivityIndicatorView

When loading an image or video that might take longer than a second, it’s a good idea to include an activity indicator on the screen.  This indicator is a spinning circle that lets the user know that something is being processed.  You can add a big sized one in the middle of your UIView.  (There is a way to add a smaller one in the tool bar, but I’m not going to discuss that one.)

The bigger activity view is part of the UIActivityIndicatorView class. There are two ways to add a UIActivityIndicatorView object. One, is to drag and drop one in your xib file.  You will want to make sure that your UIActivityIndicatorView object is on top or it won’t be visible.  This was a little tricky for me when I added one the second way – by manually coding it into your loadView (used when you don’t use a xib.)   I had added many layers on my UIView – a scrollView, then an imageView.  So, I assumed that the activity indicator would be added after the imageView.  But, it wasn’t visible.  When I added the activity indicator to the UIView first, it worked!  It was just the reverse of what I had thought.  (Though, I guess this means that the scrollView is on top of the imageView. And after I think about it, it makes sense. If the imageView was on top, you couldn’t move the imageView.)

So, I guess you would like to see some code.  Here is how to code the activity indicator in your interface file:

@property (nonatomic, retain) UIActivityIndicatorView *activityIndicator;

Then, in your loadView, initialize the activityIndicator and add it to your UIView:

activityIndicator = [[[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:

  UIActivityIndicatorViewStyleGray]autorelease];

activityIndicator.frame = CGRectMake(0.0f, 0.0f, 32.0f, 32.0f);

 activityIndicator.hidesWhenStopped = YES;

[myView addSubview:activityIndicator];

activityIndicator.center = myView.center;

I’ve initialized the style large gray to be autoreleased. I made the frame a certain size.  Then, I changed hidesWhenStopped to YES, so the indicator disappears when it’s not spinning anymore. I added the activity indicator to my UIView, myView.  Finally, I centered the indicator to the center of my view.

When I want the activity indicator to spin, I use the code:

[activityIndicator startAnimating];

When I want the activity indicator to stop spinning, just use this code:

[activityIndicator stopAnimating];

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>