0

以前有人问过这个问题,但答案不起作用。我知道(如果我错了,请纠正我)主线程更新 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部分并不短,按下按钮时运行代码实际上需要5s,所以它不是更新得那么快我看不到它。

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

4

2 回答 2

0

你还需要在另一个线程上“做东西”,否则它仍然会阻塞你的主线程。请注意,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];
            });
        }
    });
}
于 2014-01-29T16:10:06.190 回答
-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];
         }
于 2014-01-29T16:03:34.033 回答