Domanda

I have a view controller that segues to a second view controller which loads several images but it hangs for a second or two before seguing from the first VC to the second. I am trying to add a UIActivityIndicatorView so that the user doesn't think the app is frozen (which is currently what it feels like). However I can't seem to get it to work properly and all of the examples I've seen are using a web view or are accessing some kind of data from a server whereas I'm loading images that are stored in the app.

I have some code below to show what I have attempted.

.h file

@interface SecondViewController: UIViewController
@property (strong, nonatomic) UIActivityIndicatorView *indicator;

.m file

-(void)viewWillAppear:(BOOL)animated
{
    self.indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];

    self.indicator.center = CGPointMake(160, 240);

    [self.view addSubview:self.indicator];

    //Loading a lot of images in a for loop.
    //The images are attached to buttons which the user can press to bring up
    //an exploded view in a different controller with additional information
    [self.indicator startAnimating];
    for{....}
    [self.indicator stopAnimating];
}

I have tried also using dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) immediately after the call to [self.indicator startAnimating] but all that happened was that the view controller loaded instantly and the images/buttons never loaded at all.

How can I get rid of the delay when the user clicks the "next" button on the first view controller? The app hangs on the first VC for about a second or two then finally loads the second view controller with all the images/buttons. Do I need to add the UIActivityIndicatorView to the first view controller instead or am I going about this completely the wrong way? I'm open to any and all methods to get this done, thanks in advance.

È stato utile?

Soluzione

You need to call the initialization code and stopAnimating in the next run loop. One easy thing you can do is the following:

-(void)viewWillAppear:(BOOL)animated
{
    self.indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    self.indicator.center = CGPointMake(160, 240);

    [self.view addSubview:self.indicator];

    //Loading a lot of images in a for loop.
    //The images are attached to buttons which the user can press to bring up
    //an exploded view in a different controller with additional information
    [self.indicator startAnimating];
    [self performSelector:@selector(loadUI) withObject:nil afterDelay:0.01];
}

-(void) loadUI {
    for{....}
    [self.indicator stopAnimating];
}

Of course there are other ways to run loadUI in the next run loop (such as using a timer).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top