How to synchronise UIViewControllerInteractiveTransitioning and CABasicAnimation

Viewed 87

I have a button in a view controller that has a shadow. This shadow is applied with an animation, in viewWillAppear.

The button is inside an empty view called 'buttonContainer'.

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    
    CATransaction.begin()
    CATransaction.setCompletionBlock {
        self.buttonContainer.layer.shadowOpacity = 1
    }
    
    let animation = CABasicAnimation(keyPath: "shadowOpacity")
    animation.fromValue = buttonContainer.layer.shadowOpacity
    animation.toValue = 1
    animation.duration = 0.6
    buttonContainer.layer.add(animation, forKey: animation.keyPath)
    
    CATransaction.commit()
}

I want the shadow to animate with the push animation of the view controller. I started implementing 'UIViewControllerAnimatedTransitioning' and I couldn't find a way to tie in the animation duration with CABasicAnimation.

func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {

    let containerView = transitionContext.containerView
    let button = containerView.viewWithTag(68) as! UIButton

    let animation = CABasicAnimation(keyPath: "shadowOpacity")
    animation.fromValue = ?
    animation.toValue = ?
}

And I suppose I would need to implement UIViewControllerInteractiveTransitioning but I can't think of a way to tie in CABasicAnimation. Any help appreciated

1 Answers

After doing some reading around it looks like someone has implemented a bridge between lower level CALayer animations and 'UIViewControllerInteractiveTransitioning'

https://github.com/stringcode86/UIPercentDrivenInteractiveTransitionWithCABasicAnimation/blob/master/InteractiveTransition/SCPercentDrivenInteractiveTransition.m

But it was done a long time ago and I haven't had time to verify it. One thing for sure is that it looks pretty ugly.

The UIViewPropertyAnimator class was released in iOS 10 and was meant to help out with this bridging by providing coordination with functions like 'addAnimation' and 'addCompletion'.

These guys have managed to implement a clean solution for bridging animations of 'CALayer' with 'UIViewControllerInteractiveTransitioning' via UIViewPropertyAnimator.

https://github.com/hedjirog/CustomPresentation

In summary It's too hard. Don't bother.

Related