ytpm
ytpm

Reputation: 5160

Adding a fade in animation to UIViewController appearance

When I change UIViewController with this method, it just appears without any animation. I want to add a fade in animation to the view, how could I do that?

- (void)changeToRootViewController:(UIViewController*)viewController forNavigationController:(UINavigationController*)naviController class:(Class)class
{
    if ([[naviController.viewControllers lastObject] isKindOfClass:[class class]])
    {
        NSLog(@"Already inside %@.", NSStringFromClass(class));
        return;
    }

    [naviController popToRootViewControllerAnimated:NO];
    NSMutableArray *viewControllers = [[NSMutableArray alloc] initWithArray:naviController.viewControllers];
    [viewControllers removeObjectAtIndex:0];
    naviController.viewControllers = viewControllers;
    [naviController pushViewController:viewController animated:YES];
}

Upvotes: 0

Views: 2555

Answers (2)

Uttam Sinha
Uttam Sinha

Reputation: 722

You can try something like this :

CATransition* transition = [CATransition animation];
transition.duration = 0.3;
transition.type = kCATransitionFade;
transition.subtype = kCATransitionFromTop;

[self.navigationController.view.layer addAnimation:transition forKey:kCATransition];
[self.navigationController pushViewController:yourViewController animated:NO];

Upvotes: 7

Wain
Wain

Reputation: 119041

You should make a single change to the navigation controller, not two:

[naviController setViewControllers:@[ viewController ] animated:YES];

which will replace the existing stack of controllers with your one controller, using the appropriate animation.

Assuming that you class check is really looking for the same instance rather than just the same class of view controller then you can actually replace all of this method with that one line.

If you want to leave some view controllers in the stack then create a mutable copy of the viewControllers, edit its contents and then set that array as the view viewController array, with animation.

Upvotes: 1

Related Questions