Change tabbarController's tab programmatically with animation

后端 未结 3 1176
不知归路
不知归路 2021-01-14 16:11

I want to change tab through code with animation. Exact scenario is that there are 2 tabs with below hierarchy.

First tab
  - Navigation controller
    - Log         


        
3条回答
  •  天涯浪人
    2021-01-14 16:23

    Below is the code I used to animate screens with slide in-out effect. Found on SO question.

    - (void)logoutButtonPressed
    {
        [self.navigationController popToRootViewControllerAnimated:NO];
    
        [self animateTransitionBetweenControllers];
    }
    
    // Animates view transition that happens from screen with logout button to login screen
    - (void)animateTransitionBetweenControllers
    {
        // Get the views to animate.
        UIView * fromView = self.tabBarController.selectedViewController.view;
        UIView * toView = [[self.tabBarController.viewControllers objectAtIndex:0] view];
    
        // Get the size of the view.
        CGRect viewSize = fromView.frame;
    
        // Add the view that we want to display to superview of currently visible view.
        [fromView.superview addSubview:toView];
    
        // Position it off screen. We will animate it left to right slide.
        toView.frame = CGRectMake(-self.view.bounds.size.width, viewSize.origin.y, toView.bounds.size.width, viewSize.size.height);
    
        // Animate transition
        [UIView animateWithDuration:0.3 delay:0.0 options:UIViewAnimationOptionTransitionNone animations:^{
            // Animate the views with slide.
            fromView.frame = CGRectMake(self.view.bounds.size.width, viewSize.origin.y, toView.bounds.size.width, viewSize.size.height);
            toView.frame = CGRectMake(0, viewSize.origin.y, toView.bounds.size.width, viewSize.size.height);
        } completion:^(BOOL finished) {
            if (finished)
            {
                // Remove the old view.
                [fromView removeFromSuperview];
                self.tabBarController.selectedIndex = 0;
            }
        }];
    }
    

提交回复
热议问题