首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在for循环中显示MBProgressHUD

在for循环中显示MBProgressHUD
EN

Stack Overflow用户
提问于 2013-01-02 21:37:59
回答 1查看 1K关注 0票数 0

我有一个这样的案例:我的应用程序需要将图像上传到服务器,我想向用户显示上传状态。例如,我选择了4张图片,当app上传图片1时,hud文本标签应该在上传图片2时显示“上传图片1/4”,显示“上传图片2/4”等,我不想将上传过程放在后台,所以假设上传过程在主线程中执行。因此,在上传图片时,主线程会被阻塞。所以hud的事情不会立即起作用。如何解决这个问题,有人能帮上忙吗?我的代码是这样的:

代码语言:javascript
复制
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.dimBackground = YES;
        hud.labelText = @"";
        //show the hud
        for (int i = 0;i<[self.images count];i++) {
            hud.labelText = self.maskTitle;//change hud lable text
            [self uploadImage:i];//upload image, this would take long, will block main thread
        }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-01-02 21:56:38

你永远不应该在主线程上执行繁重的操作,但是如果你真的想这样做,你可以这样做

代码语言:javascript
复制
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.dimBackground = YES;
hud.labelText = @"";
//show the hud
for (int i = 0;i<[self.images count];i++) {
    hud.labelText = self.maskTitle;//change hud lable text
    [self performSelector:@selector(uploadImage:) withObject:@i afterDelay:0.001];        
}

插入延迟将允许NSRunLoop在您开始上载图像之前完成其周期,以便更新UI。这是因为UIKit在NSRunLoop的当前迭代结束时绘制。

另一种方法是手动运行NSRunLoop,例如

代码语言:javascript
复制
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.dimBackground = YES;
hud.labelText = @"";
//show the hud
for (int i = 0;i<[self.images count];i++) {
    hud.labelText = self.maskTitle;//change hud lable text
    [[NSRunLoop currentRunLoop] runUntilDate:[NSDate distantPast]];
    [self performSelector:@selector(uploadImage:) withObject:@i afterDelay:0];        
}

请注意,在这两个示例中,您的uploadImage:方法现在都需要接受NSNumber而不是int

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14123108

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档