2010-04-16 106 views
4

我有一種方法,其中動畫UIWindow的子視圖之一,然後使用removeFromSuperviewUIWindow刪除它。但是,當我動畫塊後放入removeFromSuperview,動畫從來沒有顯示,因爲removeFromSuperview去除UIWindowUIView播放動畫:-(之前,我怎樣才能延緩removeFromSuperview所以播放動畫,然後再子視圖被刪除?我的動畫後試圖[NSThread sleepForTimeInterval:1];阻止,但沒有獲得預期效果,因爲動畫睡覺也因爲某些原因UIView removeFromSuperView動畫延遲

我對這個方法的代碼:

- (void) animateAndRemove 
    { 
    NSObject *mainWindow = [[UIApplication sharedApplication] keyWindow]; 

    [UIView beginAnimations:nil context:nil]; 
     [UIView setAnimationDuration:0.8]; 
    UIView *theView = nil; 
    for (UIView *currentView in [mainWindow subviews]) 
    { 
     if (currentView.tag == 666) 
     { 
     currentView.backgroundColor = [UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:0.0]; 
     theView = currentView; 
     } 
    } 
    [UIView setAnimationTransition: UIViewAnimationTransitionNone forView:theView cache:YES]; 
     [UIView commitAnimations]; 



//[NSThread sleepForTimeInterval:1]; 

[theView removeFromSuperview]; 


    } 

回答

16

您應該使用在動畫塊代理機制來決定什麼時做動畫結束。對於你的情況,使用

[UIView beginAnimations:nil context:nil]; 
[UIView setAnimationDelegate:theView]; 
[UIView setAnimationDidStopSelector:@selector(removeFromSuperview)]; 
.... 

這確保[theView removeFromSuperview]將在動畫完成後調用。

+0

哇,這就像一個魅力的工作!驚人!謝謝 – Mike 2010-04-16 13:16:59

+0

這是一個不錯的解決方案。可惜它沒有被接受。向上! – mtrc 2010-07-27 16:34:37

7

如果你靶向的iOS 4.0向上您可以使用動畫塊:

[UIView animateWithDuration:0.2 
    animations:^{view.alpha = 0.0;} 
    completion:^(BOOL finished){ [view removeFromSuperview]; }]; 

(上面的代碼來自蘋果的UIView的文檔)

+1

對我來說,比接受的答案更優雅的解決方案 – ehftwelve 2012-12-20 08:01:13