如何在iOS中添加MBProgressHUD等待加载数据



我有一个问题:我使用AFNetworking从服务器获取数据,我使用NSOperationQueue向其添加了许多操作,在每个请求中,我将此操作添加到队列中,并使用waitUntilAllOperationsAreFinished作为波纹管:

request 1
...
    [queue addOperation:operation1];
    [queue waitUntilAllOperationsAreFinished];
request 2
...
    [queue addOperation:operation2];
    [queue waitUntilAllOperationsAreFinished];

我尝试了上面的代码,我的程序似乎挂起了,之后,它运行正常。所以我想将MBProgressHUD添加到等待队列完成,然后我想检查队列是否完成,我想隐藏MBProgressHUD。但是当我单击按钮加载UIViewController时,MBProgressHUD无法显示。

HUD = [[MBProgressHUD alloc] initWithView:self.view];
[self.view addSubview:HUD];
HUD.delegate = self;
HUD.labelText = @"Loading";

实际上,我想在队列结束时显示MBProgressHUD。我该怎么做?谢谢大家

很快你就可以这样做了:

[MBProgressHUD showHUDAddedTo:self.view animated:YES];
[MBProgressHUD hideHUDForView:self.view animated:YES];

检查MBProgressHUD 的使用情况

另一种更好的方法。

  HUD = [[MBProgressHUD alloc] initWithView:self.view];
    HUD.labelText = @"Doing funky stuff...";
    HUD.detailsLabelText = @"Just relax";
    HUD.mode = MBProgressHUDModeAnnularDeterminate;
    [self.view addSubview:HUD];
    [HUD showWhileExecuting:@selector(doSomeFunkyStuff) onTarget:self withObject:nil animated:YES];

和做一些时髦的东西

- (void)doSomeFunkyStuff {
    float progress = 0.0;
    while (progress < 1.0) {
        progress += 0.01;
        HUD.progress = progress;
        usleep(50000);
    }
}

详细答案在这里..

waitUntilAllOperationsAreFinished会破坏当前线程,这可能是主线程,所以你真的不想这样做。

如果您使用的是AFNetworking,请在AFHTTPClient上查看此方法

- (void)enqueueBatchOfHTTPRequestOperations:(NSArray *)operations 
                              progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock 
                            completionBlock:(void (^)(NSArray *operations))completionBlock;

因此,向您展示HUD,然后调用此方法并将HUD隐藏在completionBlock

最新更新