简体   繁体   中英

Add view overlay to iPhone app

I'm trying to do something like this:

- (void)sectionChanged:(id)sender {
    [self.view addSubview:loadingView];
    // Something slow
    [loadingView removeFromSuperview];
}

where loadingView is a semi-transparent view with a UIActivityIndicatorView. However, it seems like added subview changes don't take effect until the end of this method, so the view is removed before it becomes visible. If I remove the removeFromSuperview statement, the view shows up properly after the slow processing is done and is never removed. Is there any way to get around this?

Run your slow process in a background thread:

- (void)startBackgroundTask {

    [self.view addSubview:loadingView];
    [NSThread detachNewThreadSelector:@selector(backgroundTask) toTarget:self withObject:nil];

}

- (void)backgroundTask {

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    // do the background task

    [self performSelectorOnMainThread:@selector(backgroundTaskDone) withObject:nil waitUntilDone:NO];
    [pool release];

}

- (void)backgroundTaskDone {

    [loadingView removeFromSuperview];
}

Two potential problems spring to mind, both centred around how you've implemented the 'do something slow here' code.

First off, if it's locking up the main thread then it's possible the application's UI isn't being redrawn in time to display the view, ie Add Subview, tight loop/intensive processing tying up the main thread, then immediately after the view is removed.

Secondly if the 'something slow' is being done asynchronously, then the view is being removed while the slow processing is running.

One things for sure, your requirements are as follows:

  1. Add a subview to display some kind of 'loading' view
  2. Invoke a slow running piece of functionality
  3. Once the slow running functionality completes, remove the 'loading' subview.

 - (void)beginProcessing { [self.view addSubview:loadingView]; [NSThread detachNewThreadSelector:@selector(process) toTarget:self withObject:nil]; } - (void)process { // Do all your processing here. [self performSelectorOnMainThread:@selector(processingComplete) withObject:nil waitUntilDone:NO]; } - (void)processingComplete { [loadingView removeFromSuperview]; } 

You could also achieve something similar with NSOperations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM