首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >循环中没有更新UIProgressBar

循环中没有更新UIProgressBar
EN

Stack Overflow用户
提问于 2014-01-29 15:54:57
回答 2查看 62关注 0票数 0

这个问题以前有人问过,但答案行不通。我知道(如果我错了)主线程更新UI,所以我们需要调用循环中的主线程。我正在尝试这样做,进度条只在循环结束时更新(所以从0%到100%)

这是我的密码

.h

代码语言:javascript
复制
@interface ViewController : UIViewController <UITextFieldDelegate> {
IBOutlet UIProgressView *progressBar;
float progressBarPercentage;
}
-(IBAction)button:(id)sender;

@end

.m

代码语言:javascript
复制
-(IBAction)button:(id)sender{

for (int z=0; z < 9; z++){

//do stuff

float progressBarPercentage = (1.0 / 9.0 * (z + 1));
        [self performSelectorOnMainThread:@selector(makeMyProgressBarMove) withObject:nil waitUntilDone:NO];

}

}

-(void)makeMyProgressBarMove{

    [progressBar setProgress:progressBarPercentage animated:YES];
     }

在调试模式下运行时,我注意到当它到达行[self performSelectorOnMainThread:@selector(makeMyProgressBarMove) withObject:nil waitUntilDone:NO];时,它只是重新启动循环,而不转到1makeMyProgressBarMove:

而且,//do stuff部分并不短,按下按钮时运行代码实际上需要5s,所以它不是更新得太快,我看不见它。

谢谢,如果需要更多的信息,我还是个初学者

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-01-29 16:10:06

您还需要在另一个线程上“做一些事情”,否则它仍然会阻塞您的主线程。注意,如果您已经在主线程上了,那么performSelectorOnMainThread是没有用的。

使用lib分派是因为它更容易:

代码语言:javascript
复制
-(IBAction)button:(id)sender{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        for (int z=0; z < 9; z++)
        {
            //do stuff

            float progressBarPercentage = (1.0 / 9.0 * (z + 1));

            dispatch_async(dispatch_get_main_queue(), ^{
                [progressBar setProgress:progressBarPercentage animated:YES];
            });
        }
    });
}
票数 0
EN

Stack Overflow用户

发布于 2014-01-29 16:03:34

现在试试这个

代码语言:javascript
复制
 -(IBAction)button:(id)sender{

    for (int z=0; z < 9; z++){

    //do stuff

    float progressBarPercentage = (1.0 / 9.0 * (z + 1));
            [self performSelectorOnMainThread:@selector(makeMyProgressBarMove) withObject:nil waitUntilDone:YES];

    }

    }

    -(void)makeMyProgressBarMove{

        [progressBar setProgress:progressBarPercentage animated:YES];
         }
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21436058

复制
相关文章

相似问题

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