Activity Indicator doesn't spin

丶灬走出姿态 提交于 2019-12-10 23:08:54

问题


I'm trying to add a spinning activity indicator (UIActivityIndicatorView) to my app while it parses data from the internet. I have an IBOutlet (spinner) connected to a UIActivityIndicatorView in IB. Initially I had it set up like this:

-

 (void) function {
        self.spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle: UIActivityIndicatorViewStyleWhite];
 self.spinner.hidesWhenStopped = YES;
 [spinner startAnimating];
 //parse data from internet
 [spinner stopAnimating];}

But the spinner wouldn't spin. I read that it had something to do with everything being on the same thread. So I tried this:

    - (void) newFunction {
        self.spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle: UIActivityIndicatorViewStyleWhite];
 self.spinner.hidesWhenStopped = YES;
 [spinner startAnimating];
 [NSThread detachNewThreadSelector: @selector(function) toTarget: self withObject: nil];
 [spinner stopAnimating];}

But still no luck. Any ideas? Thanks.


回答1:


Your newFunction: method should look like this:

- (void) newFunction {
   self.spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
   self.spinner.hidesWhenStopped = YES;
   [NSThread detachNewThreadSelector: @selector(function) toTarget: self withObject: nil];
}

And your function method should look like this:

- (void) function {
   NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
   [self.spinner performSelectorOnMainThread:@selector(startAnimating) withObject:nil waitUntilDone:NO];

   //...

   [self.spinner performSelectorOnMainThread:@selector(stopAnimating) withObject:nil waitUntilDone:NO];
   [pool drain];
}



回答2:


you should not intitialize indicator again .please replace your code with this.

-(void) function {
    [spinner startAnimating];
    [self performSelector:@selector(newfunction) withObject:nil afterDelay:3.0];
}
- (void) newfunction {
     [spinner stopAnimating];
}

Thanks.




回答3:


Just see that the "//parse data from internet " is synchronous or asynchronous. Asynchronous would mean that a separate thread would start from that point on, and the current function execution will continue without delay.

In your second example, you are explicitly making separate thread, which means that @selector(function) will happen on a separate thread, and the next statement [spinner stopAnimating] is executed immediately. So, it seems like spinner is not spinning at all.

Moreover, make sure you start and stop the activity indicator on main thread only.



来源:https://stackoverflow.com/questions/4481467/activity-indicator-doesnt-spin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!