iPhone UIActivityIndi​​catorView无法启动或停止

jon*_*nyv 8 iphone uiactivityindicatorview

当我在UIActivityIndi​​catorView上调用startAnimating时,它无法启动.为什么是这样?

[这是一个博客风格的自我回答的问题.下面的解决方案对我有用,但也许还有其他更好的方法?]

jon*_*nyv 16

如果您编写如下代码:

- (void) doStuff
{
    [activityIndicator startAnimating];
    ...lots of computation...
    [activityIndicator stopAnimating];
}
Run Code Online (Sandbox Code Playgroud)

您没有给UI实际启动和停止活动指示器的时间,因为您的所有计算都在主线程上.一种解决方案是在单独的线程中调用startAnimating:

- (void) threadStartAnimating:(id)data {
    [activityIndicator startAnimating];
}

- (void)doStuff
{ 
    [NSThread detachNewThreadSelector:@selector(threadStartAnimating:) toTarget:self withObject:nil];
    ...lots of computation...
    [activityIndicator stopAnimating];
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以将计算放在单独的线程上,并在调用stopAnimation之前等待它完成.


Fra*_*itt 12

我经常这样做:

[activityIndicator startAnimating];
[self performSelector:@selector(lotsOfComputation) withObject:nil afterDelay:0.01];

...

- (void)lotsOfComputation {
    ...
    [activityIndicator stopAnimating];
}
Run Code Online (Sandbox Code Playgroud)