【发布时间】:2021-01-26 10:38:53
【问题描述】:
我需要为 UIViewController 制作动画,它是 UINavigationController 的根。该导航控制器以模态方式呈现。
我知道我可以使用视图控制器的生命周期方法来做到这一点,但如果可能的话,我想使用UIViewControllerAnimatedTransitioning 来保持 VC 代码的清洁。
我尝试了以下方法:
a) 将UINavigationControllerDelegate 设置为导航控制器,这样我就可以使用这个委托函数:
func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationController.Operation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning?
但是,它只会在导航控制器(从 VC 到 VC)的转换过程中被调用。
b) 在根视图控制器中设置UIViewControllerTransitioningDelegate 并使用此委托函数:
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning?
但同样,它不会被调用,因为呈现的是导航控制器。
c) 在导航控制器中设置UIViewControllerTransitioningDelegate 并使用相同的委托函数:
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning?
在这种情况下,它会被调用,我可以注入 UIViewControllerAnimatedTransitioning 对象,但我只能考虑使用 hack 来为根设置动画,例如
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let fromVC = transitionContext.viewController(forKey: .from),
let toVC = transitionContext.viewController(forKey: .to) as? UINavigationController,
toVC.children.count == 1,
let myRootVC = toVC.children.first as? MyViewController
else {
transitionContext.completeTransition(false)
return
}
// Animate manually
myRootVC.view.alpha = 0
// [...]
}
你知道有什么方法可以很好地捕捉到这个吗?
【问题讨论】:
-
你想出解决方案了吗?我也坚持这个