iPhone UIActivityIndicatorView not starting or sto

2020-02-11 02:54发布

When I call startAnimating on a UIActivityIndicatorView, it doesn't start. Why is this?

[This is a blog-style self-answered question. The solution below works for me, but, maybe there are others that are better?]

6条回答
闹够了就滚
2楼-- · 2020-02-11 03:31

If you write code like this:

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

You aren't giving the UI time to actually start and stop the activity indicator, because all of your computation is on the main thread. One solution is to call startAnimating in a separate thread:

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

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

Or, you could put your computation on a separate thread, and wait for it to finish before calling stopAnimation.

查看更多
Rolldiameter
3楼-- · 2020-02-11 03:32

Ok, sorry seems like I went through my code being blind.

I've ended the Indicator like this:

    [activityIndicator removeFromSuperview];
activityIndicator = nil;

So after one run, the activityIndicator has been removed completely.

查看更多
老娘就宠你
4楼-- · 2020-02-11 03:43

I usually do:

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

...

- (void)lotsOfComputation {
    ...
    [activityIndicator stopAnimating];
}
查看更多
我命由我不由天
5楼-- · 2020-02-11 03:48

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];
}
查看更多
小情绪 Triste *
6楼-- · 2020-02-11 03:50

If needed, swift 3 version:

func doSomething() {
    activityIndicator.startAnimating()
    DispatchQueue.global(qos: .background).async {
        //do some processing intensive stuff
        DispatchQueue.main.async {
            self.activityIndicator.stopAnimating()
        }
    }
}
查看更多
乱世女痞
7楼-- · 2020-02-11 03:52

All UI elements require to be on main thread

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

then:

-(void)startIndicator{
    [activityIndicator startAnimating];
}
查看更多
登录 后发表回答