【问题标题】:iPhone UIActivityIndicatorView not starting or stoppingiPhone UIActivityIndi​​catorView 未启动或停止
【发布时间】:2009-12-04 22:52:54
【问题描述】:

当我在 UIActivityIndi​​catorView 上调用 startAnimating 时,它没有启动。这是为什么呢?

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

【问题讨论】:

  • 您可能想明确表示您发布的是博客风格的自我回答问题。

标签: iphone uiactivityindicatorview


【解决方案1】:

如果你写这样的代码:

- (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)
  • 这个方法是否启动一个新线程..???如果是,那么在哪里以及如何停止它..??
  • 这会产生奇怪的错误(或崩溃),因为 startAnimating 必须在主线程上调用。在另一个线程上进行计算的第二种选择是正确的方法。
【解决方案2】:

我通常这样做:

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

...

- (void)lotsOfComputation {
    ...
    [activityIndicator stopAnimating];
}

【讨论】:

  • 我也在做同样的事情,不同的是我使用 -(void)performBlock:(void (^)(void))block afterDelay:(NSTimeInterval)delay;来自forrst.com/posts/Delayed_Blocks_in_Objective_C-0Fn 当我指定 0.0 时,不显示进度指示器,而 0.01 是 100Hz 显示器闪烁之间的时间。
【解决方案3】:

这个问题很有用。但是答案帖子中缺少的一件事是,每件需要很长时间的事情都需要在单独的线程中执行,而不是在 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];
}

【讨论】:

  • 我会选择这个。这是最好的解释。不过,一个解决方法是我会移动调用以停止在您已分离的方法中为指示器设置动画。一旦方法完成,它将停止动画。
【解决方案4】:

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

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

然后:

-(void)startIndicator{
    [activityIndicator startAnimating];
}

【讨论】:

    【解决方案5】:

    如果需要,swift 3 版本:

    func doSomething() {
        activityIndicator.startAnimating()
        DispatchQueue.global(qos: .background).async {
            //do some processing intensive stuff
            DispatchQueue.main.async {
                self.activityIndicator.stopAnimating()
            }
        }
    }
    

    【讨论】:

      【解决方案6】:

      好的,抱歉,我的代码好像是盲目的。

      我已经这样结束了指标:

          [activityIndicator removeFromSuperview];
      activityIndicator = nil;
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-01
        • 2013-04-06
        相关资源
        最近更新 更多