iOS:如何正确停止 Activity 指标?

iOS: how to properly stop an Activity Indicator?

我想在 NSNotificationCenter 默认调用的方法中停止指示器的动画,方法带有 postNotificationName。 所以我在主线程上做这个

-(void)method
{
    ...
    [ind performSelectorOnMainThread:@selector(stopAnimating) withObject:nil waitUntilDone:NO];
}

没用。方法被正确调用,任何其他被调用的选择器都会完成它们的工作,但不会停止动画。 我把 [ind stopAnimating] 放在另一个函数中,然后通过 performSelectorOnMainThread 调用它,但它仍然没有工作。

尝试:

-(void)method
{
    dispatch_async(dispatch_get_main_queue(), ^{ 
       [ind stopAnimating];   
    });
}

试试这个...

创建一个停止动画的方法

-(void)stopAnimationForActivityIndicator
{
    [ind stopAnimating];
}

像这样替换你的方法 -

-(void)method
{
    ...
    [self performSelectorOnMainThread:@selector(stopAnimationForActivityIndicator) withObject:nil waitUntilDone:NO];
}

应该施展魔法...

您还可以使用以下方法在主线程中以单一方法启动和停止 activity 指标,还可以让您异步执行代码-

- (void)showIndicatorAndStartWork
{
    // start the activity indicator (you are now on the main queue)
    [activityIndicator startAnimating];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // do your background code here

        dispatch_sync(dispatch_get_main_queue(), ^{
            // stop the activity indicator (you are now on the main queue again)  
        [activityIndicator stopAnimating];
        });
    });
}