8

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

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

4

6 回答 6

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 之前等待它完成。

于 2009-12-04T23:02:16.210 回答
12

我通常这样做:

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

...

- (void)lotsOfComputation {
    ...
    [activityIndicator stopAnimating];
}
于 2009-12-24T00:05:26.567 回答
1

This question is quite useful. But one thing that is missing in the answer post is , every thing that takes long time need to be perform in separate thread not the UIActivityIndicatorView. This way it won't stop responding to UI interface.

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

    -(void)doStuff{
    [activityIndicator startAnimating]; 
    [NSThread detachNewThreadSelector:@selector(doLotsOFWork:) toTarget:self withObject:nil]; 
    [activityIndicator stopAnimating];
}
于 2012-12-19T10:38:58.973 回答
1

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

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

然后:

-(void)startIndicator{
    [activityIndicator startAnimating];
}
于 2013-08-24T12:12:44.137 回答
1

如果需要,swift 3 版本:

func doSomething() {
    activityIndicator.startAnimating()
    DispatchQueue.global(qos: .background).async {
        //do some processing intensive stuff
        DispatchQueue.main.async {
            self.activityIndicator.stopAnimating()
        }
    }
}
于 2016-10-02T06:34:54.460 回答
0

好的,抱歉,我好像是盲目地浏览了我的代码。

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

    [activityIndicator removeFromSuperview];
activityIndicator = nil;

所以在一次运行之后,activityIndi​​cator 已经被完全移除了。

于 2009-12-25T11:14:27.083 回答