Search code examples
objective-ciosuiviewuiviewcontrollercore-animation

Smoother transition from one UIView to another UIView


I have a UIViewController which has multiple subviews. Each subview is a UIView subclass, and I want to switch between views by tapping the toolbar buttons. I did this by using the animation blocks:

Example:

[UIView animateWithDuration:0.5 
                      delay:0.0 
                    options:UIViewAnimationOptionTransitionFlipFromRight 
                 animations:^{
                         [StoreView removeFromSuperview];
                         [self.view addSubview:HomeView]; 
                     }
                 completion:NULL];

Everything is working fine actually. The problem is the transition is not really smooth. For example, the HomeView has five buttons scattered (as part of the design), and whenever I switch from one view to HomeView, these buttons will come from a corner and rearrange itself after the transition, which is not exactly beautiful to look at.

So how will I make these buttons stay in place?


Solution

  • When doing animations with complex subviews you can sometimes get undesirable results as you are experiencing. Not only can some oddities appear, but they are sometimes costly depending on the complexity of the view structure. One suggestion I would make is instead of animating the complex views themselves, you could render the views to a graphics context and animate the resulting image in a UIImageView, using sleight-of-hand to make it appear that you are animating the view hierarchy. In this effect, you avoid doing what amounts to a complex transform on the HomeView and StoreView and instead do simple flip with UIImageView instances. Consider the following example code:

    UIImageView *storeImage = //  pointer to the image rendered to a graphics context
    UIImageView *homeImage =  //  pointer to the image rendered to a graphics context
    
    [self.view addSubview:storeImage];
    [storeView removeFromSuperview];
    
    [UIView animateWithDuration:0.5 
                          delay:0.0 
                        options:UIViewAnimationOptionTransitionFlipFromRight 
                     animations:^{
                             [storeImage removeFromSuperview];
                             [self.view addSubview:homeImage]; 
                         }
                     completion:^(BOOL finished) {
                         [self.view addSubview:homeView];
                         [homeImage removeFromSuperview];
                     }];