使用MBProgressHUD 的HUD不能立刻显示出来
遇到问题:
使用 MBProgressHUD,如果在一个函数中添加了 HUD,又在函数结束前做了耗时操作,此时hud 不会立刻显示出来,而是需要等到函数结束后才能显示,如下例子中,要等到for循环结束后才能显示出来。
- (IBAction)showTextOnly:(id)sender {
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
hud.mode = MBProgressHUDModeText;
hud.labelText = @"Some message...";
hud.margin = 10.f;
hud.removeFromSuperViewOnHide = YES;
for (int i=0; i<5; i++) {
sleep(1);
}
}
原因:
UIKit 不能在当前run loop结束前重画,即需要在下一个run loop 周期才能重画,更新UI。
解决方案:
你下面方法运行你的耗时程序,然后在myTadk结束时隐藏 HUD
// Setup and show HUD here
[self performSelector:@selector(myTask) withObject:nil afterDelay:0.001];
或者你可以手动的运行 run loop
// Setup and show HUD here
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate distantPast]];
// Insert myTask code here
// Hide the shown HUD here
或者使用blocks
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.001 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
// Insert myTask code here
});