当我在 UIActivityIndicatorView 上调用 startAnimating 时,它不会启动。为什么是这样?
[这是一个博客式的自我回答问题。下面的解决方案对我有用,但是,也许还有其他更好的解决方案?]
当我在 UIActivityIndicatorView 上调用 startAnimating 时,它不会启动。为什么是这样?
[这是一个博客式的自我回答问题。下面的解决方案对我有用,但是,也许还有其他更好的解决方案?]
如果你写这样的代码:
- (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 之前等待它完成。
我通常这样做:
[activityIndicator startAnimating];
[self performSelector:@selector(lotsOfComputation) withObject:nil afterDelay:0.01];
...
- (void)lotsOfComputation {
...
[activityIndicator stopAnimating];
}
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];
}
所有 UI 元素都需要在主线程上
[self performSelectorOnMainThread:@selector(startIndicator) withObject:nil waitUntilDone:NO];
然后:
-(void)startIndicator{
[activityIndicator startAnimating];
}
如果需要,swift 3 版本:
func doSomething() {
activityIndicator.startAnimating()
DispatchQueue.global(qos: .background).async {
//do some processing intensive stuff
DispatchQueue.main.async {
self.activityIndicator.stopAnimating()
}
}
}
好的,抱歉,我好像是盲目地浏览了我的代码。
我已经像这样结束了指标:
[activityIndicator removeFromSuperview];
activityIndicator = nil;
所以在一次运行之后,activityIndicator 已经被完全移除了。