Search code examples
swiftanimationtransitionuiviewanimationtransition

Swift Custom Transition Not Working (UIViewControllerTransitioningDelegate not called)


I am just trying to switch to a second view controller. I have my HomeViewController with this extension:

extension HomeViewController: UIViewControllerTransitioningDelegate {
    func animationController(forPresented presented: UIViewController,
                             presenting: UIViewController,
                             source: UIViewController)
        -> UIViewControllerAnimatedTransitioning? {
        return transition
    }

    public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return nil
    }
}

and transition defined in the class

let transition = PopAnimator()

I have a button that when it is tapped should switch view controllers and use custom transition (PopAnimator):

@objc func handleTap() {
        let viewController = ViewController()
        viewController.transitioningDelegate = self
        self.present(viewController, animated: false, completion: nil)
    }

PopAnimator class (really just a fadeIn for now):

class PopAnimator: NSObject, UIViewControllerAnimatedTransitioning {
    let duration = 1.0
    var presenting = true
    var originFrame = CGRect.zero

    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return duration
    }

    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        let containerView = transitionContext.containerView

        let toView = transitionContext.view(forKey: .to)!

        containerView.addSubview(toView)
        toView.alpha = 0.0
        UIView.animate(withDuration: duration,
        animations: {
            toView.alpha = 1.0
        },
        completion: { _ in
            transitionContext.completeTransition(true)
        }
        )
    }
}

When I click the button, it switches viewControllers but doesn't use my custom transition. If I put a breakpoint in my animationController(forPresented:presenting:source:) function or my PopAnimator class it is not reached.


Solution

  •         self.present(viewController, animated: false, completion: nil)
    

    try setting animated: true if you want animated transition