Transition behavior using transitionFromView and transitionWithView

David picture David · Aug 30, 2010 · Viewed 36.6k times · Source

I am attempting to create a transition between two subviews (view1 and view2). When a button is pressed I want view1 (front) to flip and show view2 (back). I have tried both transitionFromView and transitionWithView. Each works - but each has a problem.

transitionFromView - flips the superview (the whole window view flips, not the subviews). When this flip happens - one subview is on the front of the superview before the flip, and the other subview is on the back of the flip - as it should be. But I don't want the superview to flip, just the subviews.

transitionWithView - flips only the subviews - but the 'to' view gets displayed before the transition happens.

Anyone have a suggestion?

-(IBAction) button1action:(id) sender {  

 if ([sender tag] == 0) {  

  [UIView transitionFromView:view2 toView:view1 duration:2.0   
  options:UIViewAnimationOptionTransitionFlipFromLeft   
  completion:nil];   
}  

 else {  
  [view1 removeFromSuperview];    
  [self.view addSubview:view2];  
  [UIView transitionWithView:view2   
    duration:2.0  
    options:UIViewAnimationOptionTransitionFlipFromRight +  
    UIViewAnimationOptionShowHideTransitionViews  
      animations:^{}   
     completion:nil];  
 }
}

Answer

Erik B picture Erik B · Dec 28, 2010

You need to remove and add the subviews in the animation block. Also, I think that transitionWithView is supposed to take the super view as argument. I think what you need to do to get this right is to use a container view that is the same size as the views you want to flip.

This is copied from the documentation:

[UIView transitionWithView:containerView
       duration:0.2
       options:UIViewAnimationOptionTransitionFlipFromLeft
       animations:^{ [fromView removeFromSuperview]; [containerView addSubview:toView]; }
       completion:NULL];