首页 文章

使用自定义动画将当前视图控制器嵌入导航控制器

提问于
浏览
0

我有 vc1,它提供导航控制器,其中包含 vc2。 vc1 和导航控制器之间的 segue 是“Present Modally”,vc2 出现标准动画,从下到上。

我想在 vc1 中使用自定义过渡动画来呈现嵌入在导航控制器中的 vc2。

故事板示例

我试过了

class CustomAnimator: NSObject {
    func animationDuration() -> TimeInterval {
        return 1.0
    }

    fileprivate func animateCustomTransition(using transitionContext: UIViewControllerContextTransitioning) {
        // ...
    }
}

extension CustomAnimator: UIViewControllerAnimatedTransitioning {
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return animationDuration()
    }

    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        animateCustomTransition(using: transitionContext)
    }
}

class CustomTransitionDelegate: NSObject {
    let animator: CustomAnimator
    override init() {
        animator = CustomAnimator()
        super.init()
    }
}

extension CustomTransitionDelegate: UIViewControllerTransitioningDelegate {
    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return self.animator
    }
}

class Vc2ViewController: UIViewController {

    // ...

    var customTranstionDelegate = CustomTransitionDelegate()

    //...
}

然后:

(1)设置 vc2 的 transitioningDelegate。显然没有效果。

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let navController = segue.destination as? UINavigationController {
        if let controller = navController.viewControllers.first as? Vc2ViewController {
            controller.transitioningDelegate = controller.customTranstionDelegate
        }
    }
}

(2)子类 UINavigationController 并设置它的 transitioningDelegate。 vc2 以所需方式出现,但导航栏已消失,vc2 后的下一个视图控制器未出现在“Show”segue 上。

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let controller = segue.destination as? Vc2NavigationController {
        controller.transitioningDelegate = controller.customTranstionDelegate
    }
}

如何使用自定义过渡动画从 vc1 呈现嵌入在导航控制器中的 vc2?

1 回答

相关问题