How to change the Push and Pop animations in a navigation based app

前端 未结 25 1153
清酒与你
清酒与你 2020-11-22 12:46

I have a navigation based application and I want to change the animation of the push and pop animations. How would I do that?

Edit 2018

Ther

相关标签:
25条回答
  • 2020-11-22 12:57

    You can now use UIView.transition. Note that animated:false. This works with any transition option, pop, push, or stack replace.

    if let nav = self.navigationController
    {
        UIView.transition(with:nav.view, duration:0.3, options:.transitionCrossDissolve, animations: {
            _ = nav.popViewController(animated:false)
        }, completion:nil)
    }
    
    0 讨论(0)
  • 2020-11-22 12:57

    I found a mildly recursive way to do this that works for my purposes. I have an instance variable BOOL that I use to block the normal popping animation and substitute my own non-animated pop message. The variable is initially set to NO. When the back button is tapped, the delegate method sets it to YES and sends a new non-animated pop message to the nav bar, thereby calling the same delegate method again, this time with the variable set to YES. With the variable is set to YES, the delegate method sets it to NO and returns YES to allow the non-animated pop occur. After the second delegate call returns, we end up back in the first one, where NO is returned, blocking the original animated pop! It's actually not as messy as it sounds. My shouldPopItem method looks like this:

    - (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item 
    {
        if ([[navigationBar items] indexOfObject:item] == 1) 
        {
            [expandedStack restack];    
        }
    
        if (!progPop) 
        {
            progPop = YES;
            [navBar popNavigationItemAnimated:NO];
            return NO;
        }
        else 
        {
            progPop = NO;
            return YES;
        }
    }
    

    Works for me.

    0 讨论(0)
  • 2020-11-22 12:59

    There are UINavigationControllerDelegate and UIViewControllerAnimatedTransitioning there you can change animation for anything you want.

    For example this is vertical pop animation for VC:

    @objc class PopAnimator: NSObject, UIViewControllerAnimatedTransitioning {
    
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
        return 0.5
    }
    
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
    
        let fromViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)!
        let toViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)!
        let containerView = transitionContext.containerView()
        let bounds = UIScreen.mainScreen().bounds
        containerView!.insertSubview(toViewController.view, belowSubview: fromViewController.view)
        toViewController.view.alpha = 0.5
    
        let finalFrameForVC = fromViewController.view.frame
    
        UIView.animateWithDuration(transitionDuration(transitionContext), animations: {
            fromViewController.view.frame = CGRectOffset(finalFrameForVC, 0, bounds.height)
            toViewController.view.alpha = 1.0
            }, completion: {
                finished in
                transitionContext.completeTransition(!transitionContext.transitionWasCancelled())
        })
    }
    

    }

    And then

    func navigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        if operation == .Pop {
            return PopAnimator()
        }
        return nil;
    }
    

    Useful tutorial https://www.objc.io/issues/5-ios7/view-controller-transitions/

    0 讨论(0)
  • 2020-11-22 12:59

    I recently was trying to do something similar. I decided I didn't like the sliding animation of the UINavigationController, but I also didn't want to do the animations that UIView gives you like curl or anything like that. I wanted to do a cross fade between the views when I push or pop.

    The problem there involves the fact that the view is literally removing the view or popping one over the top of the current one, so a fade doesn't work. The solution I came to involved taking my new view and adding it as a subview to the current top view on the UIViewController's stack. I add it with an alpha of 0, then do a crossfade. When the animation sequence finishes, I push the view onto the stack without animating it. I then go back to the old topView and clean up stuff that I had changed.

    Its a little more complicated than that, because you have the navigationItems you have to adjust to make the transition look correct. Also, if you do any rotation, you then have to adjust frame sizes as you add the views as subviews so they show up correctly on screen. Here is some of the code I used. I subclassed the UINavigationController and overrode the push and the pop methods.

    -(void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
    {
          UIViewController *currentViewController = [self.viewControllers lastObject];
          //if we don't have a current controller, we just do a normal push
          if(currentViewController == nil)
          {
             [super pushViewController:viewController animated:animated];
             return;
          }
          //if no animation was requested, we can skip the cross fade
          if(!animation)
          {
             [super pushViewController:viewController animated:NO];
             return;
          }
          //start the cross fade.  This is a tricky thing.  We basically add the new view
    //as a subview of the current view, and do a cross fade through alpha values.
    //then we push the new view on the stack without animating it, so it seemlessly is there.
    //Finally we remove the new view that was added as a subview to the current view.
    
    viewController.view.alpha = 0.0;
    //we need to hold onto this value, we'll be releasing it later
        NSString *title = [currentViewController.title retain];
    
    //add the view as a subview of the current view
    [currentViewController.view addSubview:viewController.view];
    [currentViewController.view bringSubviewToFront:viewController.view];
    UIBarButtonItem *rButtonItem = currentViewController.navigationItem.rightBarButtonItem;
    UIBarButtonItem *lButtonItem = currentViewController.navigationItem.leftBarButtonItem;
    
    NSArray *array = nil;
    
    //if we have a right bar button, we need to add it to the array, if not, we will crash when we try and assign it
    //so leave it out of the array we are creating to pass as the context.  I always have a left bar button, so I'm not checking to see if it is nil. Its a little sloppy, but you may want to be checking for the left BarButtonItem as well.
    if(rButtonItem != nil)
        array = [[NSArray alloc] initWithObjects:currentViewController,viewController,title,lButtonItem,rButtonItem,nil];
    else {
        array = [[NSArray alloc] initWithObjects:currentViewController,viewController,title,lButtonItem,nil];
    }
    
    //remove the right bar button for our transition
    [currentViewController.navigationItem setRightBarButtonItem:nil animated:YES];
    //remove the left bar button and create a backbarbutton looking item
    //[currentViewController.navigationItem setLeftBarButtonItem:nil animated:NO];
    
    //set the back button
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:title style:kButtonStyle target:self action:@selector(goBack)];
    [currentViewController.navigationItem setLeftBarButtonItem:backButton animated:YES];
    [viewController.navigationItem setLeftBarButtonItem:backButton animated:NO];
    [backButton release];
    
    [currentViewController setTitle:viewController.title];
    
    [UIView beginAnimations:@"push view" context:array];
    [UIView setAnimationDidStopSelector:@selector(animationForCrossFadePushDidStop:finished:context:)];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDuration:0.80];
    [viewController.view setAlpha: 1.0];
    [UIView commitAnimations];
    }
    
    -(void)animationForCrossFadePushDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context
    {
    
    UIViewController *c = [(NSArray*)context objectAtIndex:0];
    UIViewController *n = [(NSArray*)context objectAtIndex:1];
    NSString *title     = [(NSArray *)context objectAtIndex:2];
    UIBarButtonItem *l = [(NSArray *)context objectAtIndex:3];
    UIBarButtonItem *r = nil;
    //not all views have a right bar button, if we look for it and it isn't in the context,
    //we'll crash out and not complete the method, but the program won't crash.
    //So, we need to check if it is there and skip it if it isn't.
    if([(NSArray *)context count] == 5)
        r = [(NSArray *)context objectAtIndex:4];
    
    //Take the new view away from being a subview of the current view so when we go back to it
    //it won't be there anymore.
    [[[c.view subviews] lastObject] removeFromSuperview];
    [c setTitle:title];
    [title release];
    //set the search button
    [c.navigationItem setLeftBarButtonItem:l animated:NO];
    //set the next button
    if(r != nil)
        [c.navigationItem setRightBarButtonItem:r animated:NO];
    
    
    [super pushViewController:n animated:NO];
    
     }
    

    As I mention in the code, I always have a left bar button item, so I don't check to see if it is nil before putting it in the array that I pass as the context for the animation delegate. If you do this, you may want to make that check.

    The problem I found was that if you crash at all in the delegate method, it won't crash the program. It just stops the delegate from completing but you don't get any kind of warning.
    So since I was doing my cleanup in that delegate routine, it was causing some weird visual behavior since it wasn't finishing the cleanup.

    The back button I create calls a "goBack" method, and that method just calls the pop routine.

    -(void)goBack
    { 
         [self popViewControllerAnimated:YES];
    }
    

    Also, here is my pop routine.

    -(UIViewController *)popViewControllerAnimated:(BOOL)animated
    {
        //get the count for the number of viewControllers on the stack
    int viewCount = [[self viewControllers] count];
    //get the top view controller on the stack
    UIViewController *topViewController = [self.viewControllers objectAtIndex:viewCount - 1];
    //get the next viewController after the top one (this will be the new top one)
    UIViewController *newTopViewController = [self.viewControllers objectAtIndex:viewCount - 2];
    
    //if no animation was requested, we can skip the cross fade
    if(!animated)
    {
        [super popViewControllerAnimated:NO];
                return topViewController;
    }
    
    
    
    //start of the cross fade pop.  A bit tricky.  We need to add the new top controller
    //as a subview of the curent view controler with an alpha of 0.  We then do a cross fade.
    //After that we pop the view controller off the stack without animating it.
    //Then the cleanup happens: if the view that was popped is not released, then we
    //need to remove the subview we added and change some titles back.
    newTopViewController.view.alpha = 0.0;
    [topViewController.view addSubview:newTopViewController.view];
    [topViewController.view bringSubviewToFront:newTopViewController.view];
    NSString *title = [topViewController.title retain];
    UIBarButtonItem *lButtonItem = topViewController.navigationItem.leftBarButtonItem;
    UIBarButtonItem *rButtonItem = topViewController.navigationItem.rightBarButtonItem;
    
    //set the new buttons on top of the current controller from the new top controller
    if(newTopViewController.navigationItem.leftBarButtonItem != nil)
    {
        [topViewController.navigationItem setLeftBarButtonItem:newTopViewController.navigationItem.leftBarButtonItem animated:YES];
    }
    if(newTopViewController.navigationItem.rightBarButtonItem != nil)
    {
        [topViewController.navigationItem setRightBarButtonItem:newTopViewController.navigationItem.rightBarButtonItem animated:YES];
    }
    
    [topViewController setTitle:newTopViewController.title];
    //[topViewController.navigationItem.leftBarButtonItem setTitle:newTopViewController.navigationItem.leftBarButtonItem.title];
    
    NSArray *array = nil;
    if(rButtonItem != nil)
        array = [[NSArray alloc] initWithObjects:topViewController,title,lButtonItem,rButtonItem,nil];
    else {
        array = [[NSArray alloc] initWithObjects:topViewController,title,lButtonItem,nil];
    }
    
    
    [UIView beginAnimations:@"pop view" context:array];
    [UIView setAnimationDidStopSelector:@selector(animationForCrossFadePopDidStop:finished:context:)];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDuration:0.80];
    [newTopViewController.view setAlpha: 1.0];
    [UIView commitAnimations];
    return topViewController;
    
     }
    
     -(void)animationForCrossFadePopDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context
     {
    
    UIViewController *c = [(NSArray *)context objectAtIndex:0];
    //UIViewController *n = [(NSArray *)context objectAtIndex:1];
    NSString *title = [(NSArray *)context objectAtIndex:1];
    UIBarButtonItem *l = [(NSArray *)context objectAtIndex:2];
    UIBarButtonItem *r = nil;
    
    
    
    //Not all views have a right bar button.  If we look for one that isn't there
    // we'll crash out and not complete this method, but the program will continue.
    //So we need to check if it is therea nd skip it if it isn't.
    if([(NSArray *)context count] == 4)
        r = [(NSArray *)context objectAtIndex:3];
    
    //pop the current view from the stack without animation
    [super popViewControllerAnimated:NO];
    
    //if what was the current veiw controller is not nil, then lets correct the changes
    //we made to it.
    if(c != nil)
    {
        //remove the subview we added for the transition
        [[c.view.subviews lastObject] removeFromSuperview];
        //reset the title we changed
        c.title = title;
        [title release];
        //replace the left bar button that we changed
        [c.navigationItem setLeftBarButtonItem:l animated:NO];
        //if we were passed a right bar button item, replace that one as well
        if(r != nil)
            [c.navigationItem setRightBarButtonItem:r animated:NO];
        else {
            [c.navigationItem setRightBarButtonItem:nil animated:NO];
        }
    
    
     }
    }
    

    That's pretty much it. You'll need some additional code if you want to implement rotations. You'll need to set the frame size of your views that you add as subviews before you show them otherwise you'll run into issues the orientation is landscape, but the last time you saw the previous view it was portrait. So, then you add it as a sub view and fade it in but it shows up as portrait, then when we pop without animation, the same view, but the one that is in the stack, now is landscape. The whole thing looks a little funky. Everyone's implementation of rotation is a little different so I didn't include my code for that here.

    Hope it helps some people. I've looked all over for something like this and couldn't find anything. I don't think this is the perfect answer, but it is working real well for me at this point.

    0 讨论(0)
  • 2020-11-22 13:00

    This is how I've always managed to complete this task.

    For Push:

    MainView *nextView=[[MainView alloc] init];
    [UIView  beginAnimations:nil context:NULL];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:0.75];
    [self.navigationController pushViewController:nextView animated:NO];
    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.navigationController.view cache:NO];
    [UIView commitAnimations];
    [nextView release];
    

    For Pop:

    [UIView  beginAnimations:nil context:NULL];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:0.75];
    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self.navigationController.view cache:NO];
    [UIView commitAnimations];
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDelay:0.375];
    [self.navigationController popViewControllerAnimated:NO];
    [UIView commitAnimations];
    


    I still get a lot of feedback from this so I'm going to go ahead and update it to use animation blocks which is the Apple recommended way to do animations anyway.

    For Push:

    MainView *nextView = [[MainView alloc] init];
    [UIView animateWithDuration:0.75
                             animations:^{
                                 [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
                                 [self.navigationController pushViewController:nextView animated:NO];
                                 [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.navigationController.view cache:NO];
                             }];
    

    For Pop:

    [UIView animateWithDuration:0.75
                             animations:^{
                                 [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
                                 [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self.navigationController.view cache:NO];
                             }];
    [self.navigationController popViewControllerAnimated:NO];
    
    0 讨论(0)
  • 2020-11-22 13:02

    Using private calls is a bad idea as Apple no longer approve apps that do that. Maybe you could try this:

    //Init Animation
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration: 0.50];
    
    
    [UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:self.navigationController.view cache:YES];
    
    //Create ViewController
    MyViewController *myVC = [[MyViewController alloc] initWith...];
    
    [self.navigationController pushViewController:myVC animated:NO];
    [myVC release];
    
    //Start Animation
    [UIView commitAnimations];
    
    0 讨论(0)
提交回复
热议问题