我想在内容加载时显示平显(并显示进度),但不幸的是它无法正常工作。当
statusUpdate
为 0.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;
}
除非我遗漏了什么,否则问题就出在
- (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;
}
这是我之前使用它的方法:
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;
}];
也许你可以使用 CADisplayLink 创建类似动画的东西。它将更新您的 HUD。
@interface ViewController () {
CADisplayLink *displayLink;
}
- (void)displayLinkMethod {
displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(animationMethod)];
[displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
}