使用MBProgressHUD 的HUD不能立刻显示出来

使用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
});

参考

参考来自 stack overflow 上的讨论

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值