LFHS
LFHS

Reputation: 305

Custom UIViewControllerAnimatedTransitioning shows black screen when finished

I have a segue, that is triggered via a button that shows another view controller modally over current context. I'm using a custom class to customize the transition, which is this:

class ShowAnimator: NSObject {
}


extension ShowAnimator: UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
    return 0.5
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
    guard
        let fromVC = transitionContext.viewController(forKey: .from),
        let toVC = transitionContext.viewController(forKey: .to) else {
            return
    }
    let containerView = transitionContext.containerView
    containerView.insertSubview(fromVC.view, belowSubview: toVC.view)
    let toFrame = transitionContext.finalFrame(for: toVC)
    let screenBounds = UIScreen.main.bounds
    let bottomLeftCorner = CGPoint(x: screenBounds.width, y: 0)
    let finalFrame = CGRect(origin: bottomLeftCorner, size: screenBounds.size)

    UIView.animate(withDuration: transitionDuration(using: transitionContext),
                   animations: {
                    fromVC.view.frame = finalFrame
    },
                   completion: { _ in
                    transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
    }
    )
}
}

In my main view controller, I have these relevant functions:

let showAnimator = ShowAnimator()
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let destination = segue.destination
    destination.transitioningDelegate = self
}


func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
    return nil
}
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
    return showAnimator
}

Note that this class is a ViewController as well as a UIViewControllerTransitioningDelegate However, whenever I press the button to perform my segue, it does the animation properly, but once it's finished it just shows a black screen, rather than the next ViewController.

Upvotes: 0

Views: 2044

Answers (1)

matt
matt

Reputation: 535306

One problem is this line:

containerView.insertSubview(fromVC.view, belowSubview: toVC.view)

You are inserting the fromVC view. That is wrong. It is already present (though not necessarily in the container).

And you are not inserting the toVC view. That is also wrong. You need to put it into the container.

Upvotes: 6

Related Questions