【发布时间】:2009-12-04 22:52:54
【问题描述】:
当我在 UIActivityIndicatorView 上调用 startAnimating 时,它没有启动。这是为什么呢?
[这是一个博客式的自我回答问题。下面的解决方案对我有用,但是,也许还有其他更好的解决方案?]
【问题讨论】:
-
您可能想明确表示您发布的是博客风格的自我回答问题。
标签: iphone uiactivityindicatorview
当我在 UIActivityIndicatorView 上调用 startAnimating 时,它没有启动。这是为什么呢?
[这是一个博客式的自我回答问题。下面的解决方案对我有用,但是,也许还有其他更好的解决方案?]
【问题讨论】:
标签: iphone uiactivityindicatorview
如果你写这样的代码:
- (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 之前等待它完成。
【讨论】:
startAnimating 必须在主线程上调用。在另一个线程上进行计算的第二种选择是正确的方法。
我通常这样做:
[activityIndicator startAnimating];
[self performSelector:@selector(lotsOfComputation) withObject:nil afterDelay:0.01];
...
- (void)lotsOfComputation {
...
[activityIndicator stopAnimating];
}
【讨论】:
这个问题很有用。但是答案帖子中缺少的一件事是,每件需要很长时间的事情都需要在单独的线程中执行,而不是在 UIActivityIndicatorView 中执行。这样它就不会停止响应 UI 界面。
- (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 就被完全移除了。
【讨论】: