2010-01-05 47 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() 
              })