无法正确显示 MBProgressHUD 进度动画

Can't display MBProgressHUD progress animation properly

我想在内容加载时显示一个 HUD(并显示进度),但不幸的是它不能正常工作。当 statusUpdate0.100000 时,屏幕上会出现 hud,但加载栏不会移动,直到 statusUpdate 不是 1.000000 并且页面加载完成。 (视图成功加载后,它会从 0-100% 进行动画处理。)如果有人能告诉我我做错了什么,我将不胜感激。

// ViewDidLoad    
[self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL];

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {

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

    [HUD show:YES];
    [self hud:self.webView.estimatedProgress];
    if ([keyPath isEqualToString:@"estimatedProgress"] && object == self.webView) {

  //   [self.progressView setAlpha:1.0f];

 //    [self.progressView setProgress:self.webView.estimatedProgress animated:YES];



        NSLog(@"%f", self.webView.estimatedProgress);

   }
    else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];


          NSLog(@"%f", self.webView.estimatedProgress);
    }
}

- (void) hud: (double)statusUpdate  {

    NSLog(@"STATUS %f", statusUpdate);

    int myInt = (int)statusUpdate;

    HUD.progress = (float)myInt;

}

这是我之前的使用方式:

UIViewController *vc = [UIApplication sharedApplication].keyWindow.rootViewController;

    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:vc.view animated:YES];
    hud.mode = MBProgressHUDModeAnnularDeterminate;
    hud.progress = 0;
    hud.labelText = NSLocalizedString(@"Loading...", nil);

[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
        CGFloat progressValue = ((CGFloat)totalBytesRead/(CGFloat)totalBytesExpectedToRead);
        MBProgressHUD *hud = [MBProgressHUD HUDForView:vc.view];
        hud.progress = progressValue;
    }];

除非我遗漏了什么,否则问题出在 - (void) hud: (double)statusUpdate

出于某种原因,您将值(statusUpdate,即 double)转换为 int,然后再次转换为 float,这意味着 0.x 值变为 0.0 并且 1.x 值变为 1.0(这就是为什么这些是 HUD 获得的唯一值 - 因为您的范围是 0.0/1.0)

一个简单的修复是这样的:

- (void) hud: (double)statusUpdate  {

    NSLog(@"STATUS %f", statusUpdate);

    HUD.progress = statusUpdate;

}

或许您可以使用 CADisplayLink 创建类似动画的内容。它将更新您的 HUD。

@interface ViewController () {
    CADisplayLink *displayLink;
}
- (void)displayLinkMethod {    
    displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(animationMethod)];
        [displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
}