2010-01-05 40 views
31

我想動畫從子視圖轉換回超級視圖。動畫removeFromSuperview

我顯示使用子視圖:

[UIView beginAnimations:@"curlup" context:nil]; 
[UIView setAnimationDelegate:self]; 
[UIView setAnimationDuration:.5]; 
[UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:self.view cache:YES]; 
[self.view addSubview:self.mysubview.view]; 
[UIView commitAnimations]; 

上述工程細。它要回超認爲,我沒有得到任何動畫:

[UIView beginAnimations:@"curldown" context:nil]; 
[UIView setAnimationDelegate:self]; 
[UIView setAnimationDuration:.5]; 
[UIView setAnimationTransition:UIViewAnimationTransitionCurlDown forView:self.view cache:YES]; 
[self.view removeFromSuperview]; 
[UIView commitAnimations]; 

有什麼不同,我應該怎樣做才能讓子視圖移除時的動畫?

回答

23

我認爲你需要做forView:self.view.superview而不是爲了與你在添加時所做的一致,因爲在這種情況下self.view是孩子,所以你需要在父母身上做。

+0

它工作得很好...;) – 2011-01-11 08:42:59

97

如果你靶向的iOS 4.0向上可以用動畫塊來代替:

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

(上面的代碼來自Apple's UIView documentation

+3

謝謝。這很簡單。 – 2011-05-05 08:55:33

+0

唉!我一直認爲*移除*需要0.2秒。但刪除發生瞬間。 * alpha更改*,需要0.2秒。如果我們再次將其設置爲200秒,仍然可以立即從超級視圖移除,但直到200秒後纔會發生。 – Honey 2017-10-11 19:18:55

1

雖然從動畫完成塊發送removeFromSuperview消息的方式工作得很好大多數情況下,有時無法防止視圖從視圖層次結構中立即移除。

例如,MKMapView在收到消息removeAnnotations後會刪除其子視圖,並且API中沒有「此動畫」備選消息。

儘管如此,下面的代碼可以讓你做任何你有一個視圖的視覺克隆就像是從上海華盈刪除後甚至釋放:

UIView * snapshotView = [view snapshotViewAfterScreenUpdates:NO]; 
snapshotView.frame = view.frame; 
[[view superview] insertSubview:snapshotView aboveSubview:view]; 

// Calling API function that implicitly triggers removeFromSuperview for view 
[mapView removeAnnotation: annotation]; 

// Safely animate snapshotView and release it when animation is finished 
[UIView animateWithDuration:1.0 
        snapshotView.alpha = 0.0; 
       } 
       completion:^(BOOL finished) { 
        [snapshotView removeFromSuperview]; 
       }]; 
9

JosephH答案斯威夫特:

UIView.animateWithDuration(0.2, animations: {view.alpha = 0.0}, 
           completion: {(value: Bool) in 
               view.removeFromSuperview() 
              })