2016-04-08 97 views
0

我有一個按鈕,當按下一個單獨的線程開始顯示加載動畫時。這樣做的原因是,只要按下按鈕就會顯示加載gif,另一個過程繼續,並在完成警報顯示時顯示。我的問題是在警報關閉後隱藏動畫。在另一個線程中隱藏加載動畫,在另一個線程中完成任務

- (IBAction)buttonPressed:(id)sender { 
    [NSThread detachNewThreadSelector:@selector(loadAnimation) toTarget:self withObject:nil]; 

    ... do other things; 

    UIAlertView *alert = [[UIAlertView alloc]initWithTitle: @"Complete" message:@"other things done" delegate: self cancelButtonTitle:@"OK" otherButtonTitles: nil]; 
    [alert setTag:1]; 
    [alert show]; 
} 

-(void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { 
    if (alertView.tag == 1) { 
     loadingGif.hidden=YES; 
    } 
} 

加載GIF:

- (void) loadAnimation { 
loadingGif.hidden=NO; 
NSArray *imageArray = [[NSArray alloc] initWithObjects:[UIImage imageNamed:@"0.gif"], [UIImage imageNamed:@"1.gif"], [UIImage imageNamed:@"2.gif"], [UIImage imageNamed:@"3.gif"], nil]; 

loadingGif = [[UIImageView alloc] initWithFrame:CGRectMake(487, 520, 50, 50)]; 
[self.view addSubview:loadingGif]; 
loadingGif.animationImages = imageArray; 
loadingGif.animationDuration = 1.5; 
[loadingGif startAnimating]; 
} 

動畫加載罰款,但一旦從警報確定已經被點擊它不會停止。一旦在主線程中啓動動畫,是否可以隱藏動畫?

回答

1

我不確定你應該在主線程以外的線程上進行UI更改。另一種方法是立即顯示動畫和使用的NSTimer來安排其他的東西,在此後不久,執行:

- (IBAction)buttonPressed:(id)sender { 

    // load animation on the main thread 
    [self loadAnimation]; 

    // start a timer to do other stuff in 1 ms (will get executed on main thread) 
    [NSTimer scheduledTimerWithTimeInterval:0.001 
     target:self 
     selector:@selector(doOtherStuff) 
     userInfo:nil 
     repeats:NO]; 
} 

- (void)doOtherStuff { 

    ... do other things; 

    UIAlertView *alert = [[UIAlertView alloc]initWithTitle: @"Complete" message:@"other things done" delegate: self cancelButtonTitle:@"OK" otherButtonTitles: nil]; 
    [alert setTag:1]; 
    [alert show]; 
1

我覺得「loadAnimation」或「UIAlertView中」在後臺運行,所以setHidden是無法正常工作你要。

爲什麼你不改變你這樣的代碼,以確保「等到你的工作就完成了」和「在主線程中運行」

-

- 改變

我對不起,我使用了不必要的背景塊。 請再檢查一次。

- (IBAction)buttonPressed:(id)sender 
{ 
    [self loadAnimation]; 

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{ 
    //  ... do other things 

     dispatch_async(dispatch_get_main_queue(), ^{ 

      UIAlertView *alert = [[UIAlertView alloc]initWithTitle: @"Complete" message:@"other things done" delegate: self cancelButtonTitle:@"OK" otherButtonTitles: nil]; 
      [alert setTag:1]; 
      [alert show]; 
     }); 
    }); 
} 

-(void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex 
{ 
    if (alertView.tag == 1) 
    { 
     loadingGif.hidden=YES; 
    } 
} 
+0

我很感謝答案。這將解釋爲類似(沒有警報)確實隱藏加載gif。我會給它一個去。謝謝 – RGriffiths

+0

@ Rriffiths我改變了我的代碼,刪除不必要的塊。對不起。 – negaipro