这个问题以前有人问过,但答案行不通。我知道(如果我错了)主线程更新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,所以它不是更新得太快,我看不见它。
谢谢,如果需要更多的信息,我还是个初学者
发布于 2014-01-29 16:10:06
您还需要在另一个线程上“做一些事情”,否则它仍然会阻塞您的主线程。注意,如果您已经在主线程上了,那么performSelectorOnMainThread是没有用的。
使用lib分派是因为它更容易:
-(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-29 16:03:34
现在试试这个
-(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];
}https://stackoverflow.com/questions/21436058
复制相似问题