2009-12-04 55 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() 
     } 
    } 
} 
相關問題