iOS2012. 8. 27. 11:00

As a newcomer to IOS programming this particular issue on my first app took a bit of working out so this is a tutorial for others struggling with the same issue.

The ultimate objective of this code is to get a out like shown below

Firstly things to note.

      UI components need to stay on the main thread, the main thread needs to perform the UI updates. (Cocoa Fundamentals Guide, page 164: “All UIKit objects should be used on the main thread only.”)
      This tutorial/code sample is about adding a UIActivityIndicatorView programmatically
      You will need #import adding to your code file
      in this code activityIndicator is a property

I am not entirely sure this is the best way as I have only been doing IOS for a short while but it works for me.

So I suggest

Firstly start by creating a method where you start the whole thing off (probably triggered from a button press- in this sample it is showNearby.

Secondly create a NSTimer and start it immediately calling the show activity selector

Thirdly start your marker/pin loading method using the performSelectorInBackground method.

Finally remove the indicator when you have completed your marker/pin showing / loading
That’s it you will have a activity indicator that appears whilst loading and is removed once done.

The code for this is shown here.

-(IBAction)showNearby:(id)sender
{
    
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(ShowActivityIndicator) userInfo:nil repeats:NO];
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:UITrackingRunLoopMode];   

    [self performSelectorInBackground:@selector(loadMarkers) withObject: nil];
   
    
}

-(void)  ShowActivityIndicator
{
    
    activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] ;
    CGRect frame = activityIndicator.frame;
    frame.origin = CGPointMake(290, 12);
    frame.size = CGSizeMake(100, 100);
   
    activityIndicator.backgroundColor=[UIColor blackColor]; 
    CALayer *layer =[activityIndicator layer];
    layer.cornerRadius = 8.0;
    activityIndicator.alpha=0.7;
    activityIndicator.frame = frame;
    activityIndicator.center = self.view.center; 
    activityIndicator.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
    activityIndicator.tag = 2;
    
    [self.view addSubview:activityIndicator];
    [self.view bringSubviewToFront:activityIndicator];  
    [activityIndicator startAnimating];
}

-(void) loadMarkers
{
  //code to load markers then remove activityIndicator

[activityIndicator stopAnimating];
[activityIndicator removeFromSuperview];
}

Posted by 다오나무