Order of actions following UiButton being pressed so that a Loading gif can be displayed

StackOverflow https://stackoverflow.com/questions/18540266

  •  26-06-2022
  •  | 
  •  

سؤال

I want to be able to do the following with my ipad app:

1 - UiButton is pressed

2 - a 'Loading' animated gif is displayed

3 - after the gif is displayed the presentViewController method is used to open target page

4 - ViewDidLoad of the target page is used to access data from an SQL database (used to populate a table on that page.)

It is because the data takes time to load that I would like the animated gif to be displayed and I have the following code to do this, however it does not work. The button turns blue as it is pressed, then a there is the delay with the Loading gif only displayed very briefly just before the page changes. It seems that step 4 from above is being run before the Loading gif is displayed. Can anyone explain what I am doing wrong or how to get around this?

- (IBAction)webObservations:(id)sender {
[loadingGif setAlpha: 1];

NSArray *imageArray = [[NSArray alloc] initWithObjects:[UIImage imageNamed:@"g0.png"], [UIImage imageNamed:@"g1.png"], [UIImage imageNamed:@"g2.png"], [UIImage imageNamed:@"g3.png"], [UIImage imageNamed:@"g4.png"], [UIImage imageNamed:@"g5.png"], [UIImage imageNamed:@"g6.png"], [UIImage imageNamed:@"g7.png"], [UIImage imageNamed:@"g8.png"], [UIImage imageNamed:@"g9.png"], nil];
loadingGif = [[UIImageView alloc] initWithFrame:CGRectMake(305, 402, 152, 14)];
[self.view addSubview:loadingGif];
loadingGif.animationImages = imageArray;
loadingGif.animationDuration = 1.5;
[loadingGif startAnimating];

ObViewControllerAdminMenu *monitorMenuViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"webObservations"];
monitorMenuViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self presentViewController:monitorMenuViewController animated:YES completion:nil];

}

هل كانت مفيدة؟

المحلول 2

Very simple in the end. Thanks to Wain for pointing me in the direction.

Move loading gif animation code to its own procedure called loadAnimation. Then replace this code in the original procedure with:

[NSThread detachNewThreadSelector:@selector(loadAnimation) toTarget:self withObject:nil];

نصائح أخرى

When you call presentViewController the controllers view is loaded very shortly after that. The view is loaded on the main thread and I guess your processing is also being performed on the main thread. As such the UI will be blocked until the loading is complete.

I would suggest that you move the animated image view to the monitorMenuViewController. When the view is displayed, determine if a load is required. If it is, show and start the image animation and then start the data load on a background thread. When the load is finished, switch back to the main thread to stop the animation and display the resulting data.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top