UIViewControllerAnimatedTransitioning 在动画进出视图时显示黑屏

Posted

技术标签:

【中文标题】UIViewControllerAnimatedTransitioning 在动画进出视图时显示黑屏【英文标题】:UIViewControllerAnimatedTransitioning shows a black screen when animating to and from view 【发布时间】:2020-04-22 14:16:23 【问题描述】:

我正在尝试为我的视图控制器创建一个 easeInEaseOut 动画,但是,当我尝试为“to”和“from”视图设置动画时,“from”视图会变黑,直到动画完成。如果我只为“to”视图设置动画,那么新的视图控制器会正确设置动画,但会在“from”视图的顶部。我希望这两种观点一起移动,给人一种印象,即第一种正在滑落为第二种让路(我想被第二种推开更准确)。谁能告诉我为什么会这样?我尝试过多种设置,请参见下面的代码:

func animateTransition(using transitionContext: UIViewControllerContextTransitioning) 
        guard let toVC = transitionContext.viewController(forKey: .to), let fromVC = transitionContext.viewController(forKey: .from) else 
            dLog("No to or from VC")
            transitionContext.completeTransition(false)
            return
        

        switch animationType 
        case .present:
            dLog("Present VC")
            transitionContext.containerView.addSubview(fromVC.view)
            transitionContext.containerView.addSubview(toVC.view)
            presentAnimation(with: transitionContext, fromView: fromVC.view, toView: toVC.view)
        case .dismiss:
            dLog("Dismiss VC")
        
    

    func presentAnimation(with transitionContext: UIViewControllerContextTransitioning, fromView: UIView, toView: UIView) 
        fromView.clipsToBounds = true
        toView.clipsToBounds = true
        fromView.transform = CGAffineTransform(translationX: 0, y: 0)
        toView.transform = CGAffineTransform(translationX: toView.frame.size.width, y: 0)

        let duration = transitionDuration(using: transitionContext)

        UIView.animate(withDuration: duration, delay: 0.0, usingSpringWithDamping: 0.0, initialSpringVelocity: 0.0, options: .curveEaseInOut, animations: 
            toView.transform = CGAffineTransform(translationX: 0.0,  y: 0.0)
            fromView.transform = CGAffineTransform(translationX: -fromView.frame.size.width, y: 0)
        )  _ in
            transitionContext.completeTransition(true)
        
    

【问题讨论】:

【参考方案1】:

如果其他人为此苦苦挣扎,我想通了。您必须改用 animateKeyFrames:

UIView.animateKeyframes(withDuration: duration, delay: 0.0, options: .calculationModeLinear, animations: 
            UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 2.0) 
                toView.transform = CGAffineTransform(translationX: 0, y: 0)
            
            UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 2.0) 
                fromView.transform = CGAffineTransform(translationX: -fromView.frame.size.width, y: 0)
            
        )  _ in
            transitionContext.completeTransition(true)
        

【讨论】:

以上是关于UIViewControllerAnimatedTransitioning 在动画进出视图时显示黑屏的主要内容,如果未能解决你的问题,请参考以下文章