2014-01-29 30 views
0

此問題之前已被詢問,但答案不起作用。我知道(糾正我,如果我錯了)主線程更新UI,所以我們需要調用循環中的主線程。我想這和進度條只在循環結束更新(所以從0%到100%)UIProgressBar未在循環中更新

這裏是我的代碼

.H

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

@end 

.M `

01:

-(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秒才能在按下按鈕時運行代碼,所以它不像它的更新速度那麼快,我看不到它。

謝謝你,只是讓我知道,如果需要更多的信息,我還是個初學者

+1

你需要「做的東西」在另一個線程也,否則仍然會阻止你的主線程。請注意,如果你已經在主線程上,'performSelectorOnMainThread'沒有用處。 – Taum

+0

我在ViewController.m,是一個主線程? – uti0mnia

+0

progressBarPercentage是在IBAction內部還是外部聲明? – Piyuesh

回答

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

是否有任何「)」缺失?我收到錯誤 – uti0mnia

+0

是的,對不起。這應該是固定的! – Taum

+0

好的,我會試試這個 – uti0mnia

0

現在試試這個

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

我已經嘗試過,它做了同樣的事情:( – uti0mnia

+0

我剛剛檢查了調試器,它正在移動到'makeMyProgreeBarMove:'方法,但它仍然沒有更新進度條 – uti0mnia