Подтвердить что ты не робот

Пользовательская анимация перехода контроллера навигации

Я слежу за некоторыми учебниками для создания пользовательской анимации при переходе от одного представления к другому.

Мой тестовый проект с использованием пользовательского segue из здесь работает отлично, но кто-то сказал мне, что он больше не поощряется делать пользовательскую анимацию в пользовательском сегменте, и я должен использовать UIViewControllerAnimatedTransitioning.

Я следил за несколькими учебниками, которые используют этот протокол, но все они касаются модальной презентации (например, этот учебник).

То, что я пытаюсь сделать, это нажать сегу в дереве контроллера навигации, но когда я пытаюсь сделать то же самое с show (push) segue, он больше не работает.

Скажите, пожалуйста, правильный способ сделать пользовательскую переходную анимацию из одного представления в другое в навигационном контроллере.

И все-таки я могу использовать один метод для всех переходных анимаций? Было бы неудобно, если в один прекрасный день я захочу сделать одну и ту же анимацию, но в итоге мне придется дважды дублировать код, чтобы работать на переход от modal vs controller.

4b9b3361

Ответ 1

Чтобы выполнить пользовательский переход с навигационным контроллером (UINavigationController), вы должны:

  • Определите свой контроллер представления для соответствия протоколу UINavigationControllerDelegate. Например, вы можете иметь расширение частного класса в вашем контроллере представления .m, который указывает соответствие этому протоколу:

    @interface ViewController () <UINavigationControllerDelegate>
    
    @end
    
  • Убедитесь, что вы фактически указали свой контроллер представления в качестве делегата контроллера навигации:

    - (void)viewDidLoad {
        [super viewDidLoad];
    
        self.navigationController.delegate = self;
    }
    
  • Внесите animationControllerForOperation в контроллер вашего вида:

    - (id<UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController
                                      animationControllerForOperation:(UINavigationControllerOperation)operation
                                                   fromViewController:(UIViewController*)fromVC
                                                     toViewController:(UIViewController*)toVC
    {
        if (operation == UINavigationControllerOperationPush)
            return [[PushAnimator alloc] init];
    
        if (operation == UINavigationControllerOperationPop)
            return [[PopAnimator alloc] init];
    
        return nil;
    }
    
  • Реализовать аниматоры для анимации push и pop, например:

    @interface PushAnimator : NSObject <UIViewControllerAnimatedTransitioning>
    
    @end
    
    @interface PopAnimator : NSObject <UIViewControllerAnimatedTransitioning>
    
    @end
    
    @implementation PushAnimator
    
    - (NSTimeInterval)transitionDuration:(id <UIViewControllerContextTransitioning>)transitionContext
    {
        return 0.5;
    }
    
    - (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext
    {
        UIViewController* toViewController   = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    
        [[transitionContext containerView] addSubview:toViewController.view];
    
        toViewController.view.alpha = 0.0;
    
        [UIView animateWithDuration:[self transitionDuration:transitionContext] animations:^{
            toViewController.view.alpha = 1.0;
        } completion:^(BOOL finished) {
            [transitionContext completeTransition:![transitionContext transitionWasCancelled]];
        }];
    }
    
    @end
    
    @implementation PopAnimator
    
    - (NSTimeInterval)transitionDuration:(id <UIViewControllerContextTransitioning>)transitionContext
    {
        return 0.5;
    }
    
    - (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext
    {
        UIViewController* toViewController   = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
        UIViewController* fromViewController = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    
        [[transitionContext containerView] insertSubview:toViewController.view belowSubview:fromViewController.view];
    
        [UIView animateWithDuration:[self transitionDuration:transitionContext] animations:^{
            fromViewController.view.alpha = 0.0;
        } completion:^(BOOL finished) {
            [transitionContext completeTransition:![transitionContext transitionWasCancelled]];
        }];
    }
    
    @end
    

    Это приведет к постепенному переходу, но вы можете свободно настраивать анимацию по своему усмотрению.

  • Если вы хотите обрабатывать интерактивные жесты (например, что-то вроде собственного прокрутки слева направо, чтобы поп), вам необходимо реализовать контроллер взаимодействия:

    • Определите свойство для контроллера взаимодействия (объект, который соответствует UIViewControllerInteractiveTransitioning):

      @property (nonatomic, strong) UIPercentDrivenInteractiveTransition *interactionController;
      

      Этот UIPercentDrivenInteractiveTransition - хороший объект, который делает тяжелый подъем обновления пользовательской анимации, основываясь на том, насколько завершен жест.

    • Добавьте к вашему виду распознаватель жестов. Здесь я просто внедряю левый распознаватель жестов, чтобы имитировать поп:

      UIScreenEdgePanGestureRecognizer *edge = [[UIScreenEdgePanGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFromLeftEdge:)];
      edge.edges = UIRectEdgeLeft;
      [view addGestureRecognizer:edge];
      
    • Внедрите обработчик распознавателя жестов:

      /** Handle swipe from left edge
       *
       * This is the "action" selector that is called when a left screen edge gesture recognizer starts.
       *
       * This will instantiate a UIPercentDrivenInteractiveTransition when the gesture starts,
       * update it as the gesture is "changed", and will finish and release it when the gesture
       * ends.
       *
       * @param   gesture       The screen edge pan gesture recognizer.
       */
      
      - (void)handleSwipeFromLeftEdge:(UIScreenEdgePanGestureRecognizer *)gesture {
          CGPoint translate = [gesture translationInView:gesture.view];
          CGFloat percent   = translate.x / gesture.view.bounds.size.width;
      
          if (gesture.state == UIGestureRecognizerStateBegan) {
              self.interactionController = [[UIPercentDrivenInteractiveTransition alloc] init];
              [self popViewControllerAnimated:TRUE];
          } else if (gesture.state == UIGestureRecognizerStateChanged) {
              [self.interactionController updateInteractiveTransition:percent];
          } else if (gesture.state == UIGestureRecognizerStateEnded) {
              CGPoint velocity = [gesture velocityInView:gesture.view];
              if (percent > 0.5 || velocity.x > 0) {
                  [self.interactionController finishInteractiveTransition];
              } else {
                  [self.interactionController cancelInteractiveTransition];
              }
              self.interactionController = nil;
          }
      }
      
    • В вашем делете контроллера навигации вы также должны реализовать метод interactionControllerForAnimationController delegate

      - (id<UIViewControllerInteractiveTransitioning>)navigationController:(UINavigationController *)navigationController
                               interactionControllerForAnimationController:(id<UIViewControllerAnimatedTransitioning>)animationController {
          return self.interactionController;
      }
      

Если вы google "UINavigationController настраиваемый переход учебник", и вы получите много хитов. Или см. Видеоконференции WWDC 2013.

Ответ 2

Вы можете добавить следующий код до addSubview

  toViewController.view.frame = [transitionContext finalFrameForViewController:toViewController];

Из другого вопроса custom-transition-for-push-animation-with-navigationcontroller-on-ios-9

Из документации Apple для finalFrameForViewController:

Возвращает прямоугольник конечного кадра для указанных контроллеров представления вид.

Прямоугольник, возвращаемый этим методом, представляет собой размер соответствующий вид в конце перехода. Для представления во время презентации, значение, возвращаемое этим методом может быть CGRectZero, но он также может быть допустимым прямоугольником рамки.

Ответ 3

Используя Rob и Q я идеальные ответы, вот упрощенный код Swift, используя ту же анимацию fade для .push и .pop:

extension YourViewController: UINavigationControllerDelegate {
    func navigationController(_ navigationController: UINavigationController,
                              animationControllerFor operation: UINavigationControllerOperation,
                              from fromVC: UIViewController,
                              to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {

        //INFO: use UINavigationControllerOperation.push or UINavigationControllerOperation.pop to detect the 'direction' of the navigation

        class FadeAnimation: NSObject, UIViewControllerAnimatedTransitioning {
            func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
                return 0.5
            }

            func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
                let toViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)
                if let vc = toViewController {
                    transitionContext.finalFrame(for: vc)
                    transitionContext.containerView.addSubview(vc.view)
                    vc.view.alpha = 0.0
                    UIView.animate(withDuration: self.transitionDuration(using: transitionContext),
                    animations: {
                        vc.view.alpha = 1.0
                    },
                    completion: { finished in
                        transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
                    })
                } else {
                    NSLog("Oops! Something went wrong! 'ToView' controller is nill")
                }
            }
        }

        return FadeAnimation()
    }
}

Не забудьте указать делегата в методе ViewViewView() в представлении YourViewController:

override func viewDidLoad() {
    //...
    self.navigationController?.delegate = self
    //...
}

Ответ 4

Работает как быстрая 3 и 4

@IBAction func NextView(_ sender: UIButton) {
  let newVC = self.storyboard?.instantiateViewControllerWithIdentifier(withIdentifier: "NewVC") as! NewViewController

  let transition = CATransition()
  transition.duration = 0.5
  transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
  transition.type = kCATransitionPush
  transition.subtype = kCAGravityLeft
  //instead "kCAGravityLeft" try with different transition subtypes

  self.navigationController?.view.layer.add(transition, forKey: kCATransition)
  self.navigationController?.pushViewController(newVC, animated: false)
}