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

时间:2009-12-04 22:52:54

标签: iphone uiactivityindicatorview

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

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

6 个答案:

答案 0 :(得分:16)

如果您编写如下代码:

- (void) doStuff
{
    [activityIndicator startAnimating];
    ...lots of computation...
    [activityIndicator stopAnimating];
}

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

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

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

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

答案 1 :(得分:12)

我通常会这样做:

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

...

- (void)lotsOfComputation {
    ...
    [activityIndicator stopAnimating];
}

答案 2 :(得分:1)

所有UI元素都需要在主线程上

[self performSelectorOnMainThread:@selector(startIndicator) withObject:nil waitUntilDone:NO];

然后:

-(void)startIndicator{
    [activityIndicator startAnimating];
}

答案 3 :(得分:1)

如果需要,swift 3版本:

func doSomething() {
    activityIndicator.startAnimating()
    DispatchQueue.global(qos: .background).async {
        //do some processing intensive stuff
        DispatchQueue.main.async {
            self.activityIndicator.stopAnimating()
        }
    }
}

答案 4 :(得分:0)

好的,对不起好像我的代码是盲目的。

我已经结束了这样的指标:

    [activityIndicator removeFromSuperview];
activityIndicator = nil;

因此,一次运行后,activityIndi​​cator已被完全删除。

答案 5 :(得分:0)

这个问题非常有用。但是答案文章中缺少的一件事是,需要很长时间的每件事都需要在单独的线程中执行而不是UIActivityIndi​​catorView。这样它就不会停止响应UI界面。

    - (void) doLotsOFWork:(id)data {
    //  do the work here.
}

    -(void)doStuff{
    [activityIndicator startAnimating]; 
    [NSThread detachNewThreadSelector:@selector(doLotsOFWork:) toTarget:self withObject:nil]; 
    [activityIndicator stopAnimating];
}
相关问题