2009-12-04 88 views
8

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

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

+0

你可能想使它清楚你正在发布一个博客风格自我回答的问题。 – TechZen 2009-12-04 23:34:12

回答

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

Thx为解决方案!有相同的问题..(+1) – Prine 2011-10-13 09:22:06

+0

这种方法启动一个新的线程..??如果是的话,那么以及如何阻止它.. ?? – 2012-07-26 10:50:30

+0

非常感谢解决方案..它帮助我.. – Shivaay 2013-10-15 11:48:59

12

我通常做的:

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

... 

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

这种方式对我很好。 – Arash 2011-03-31 01:41:28

+0

我正在做同样的事情,我使用的区别 - (void)performBlock:(void(^)(void))block afterDelay:(NSTimeInterval)delay;来自http://forrst.com/posts/Delayed_Blocks_in_Objective_C-0Fn当我指定0.0时,不显示进度指示器,而0.01是100Hz监视器闪烁之间的时间。 – 18446744073709551615 2011-10-11 22:39:08

+0

感谢您的解决方案... – 2013-02-21 07:13:43

0

好了,对不起,好像我通过我的代码是盲目的去了。

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

[activityIndicator removeFromSuperview]; 
activityIndicator = nil; 

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

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]; 
} 
+0

我会与这一个去。这是最好的解释。一个解决办法是,我会移动呼叫停止在您已分离的方法中指示动画。一旦方法完成,它将停止动画。 – 2014-10-15 04:15:52

1

所有UI元素要求必须在主线程

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

则:

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

如果需要的话,SWIFT版本3:

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