UIProgressBar不会在循环中更新

时间:2014-01-29 15:54:57

标签: objective-c uiprogressbar

此问题之前已被问过,但答案无效。我知道(纠正我,如果我错了)主线程更新UI,所以我们需要在循环中调用主线程。我正在尝试这个,进度条只在循环结束时更新(因此从0%变为100%)

这是我的代码

·H

@interface ViewController : UIViewController <UITextFieldDelegate> {
IBOutlet UIProgressView *progressBar;
float progressBarPercentage;
}
-(IBAction)button:(id)sender;

@end

的.m

-(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部分并不短,按下按钮时实际需要5秒来运行代码,所以它不像它更新那么快我无法看到它。

谢谢,如果需要更多信息,请告诉我,我还是初学者

2 个答案:

答案 0 :(得分:0)

你还需要在另一个线程上“Do Stuff”,否则它仍然会阻塞你的主线程。请注意,如果您已经在主线程上,则performSelectorOnMainThread没有用处。

使用 libdispatch ,因为它更容易:

-(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];
            });
        }
    });
}

答案 1 :(得分:-1)

现在试试这个

 -(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];
         }