如何将UINavigationControllerDelegate连接到导航控制器?

时间:2017-08-27 20:23:23

标签: ios swift uinavigationcontroller

ANSWER:简单的语法错误 - 设置委托时,应该读取SomeNavigationController.delegate = self,而不是SomeNavigationController.navigationController?.delegate = self

以下是创建导航控制器的基本视图控制器。我将self声明为其委托,并在该视图控制器的扩展中符合委托的协议,并创建了一个对象作为自定义动画制作者。但是此导航堆栈中的视图控制器不采用此动画;我错过了什么?

是否需要在此导航堆栈的根视图控制器中或在此堆栈中推送和弹出的视图控制器中存在任何代码?或者所有自定义动画代码都属于此处(在创建导航控制器的视图控制器中)并且我只是遗漏了什么?


查看控制器创建UINavigationController的位置

class BaseViewController: UIViewController {

    override func loadView() {
        buildNavigationController()
    }

    func buildNavigationController() {
        let SomeNavigationControllerRoot = SomeViewController()
        let SomeNavigationController = UINavigationController(rootViewController: SomeNavigationControllerRoot)
        SomeNavigationController.delegate = self
        view.addSubview(SomeNavigationController.view)
    }

}

extension BaseViewController: UINavigationControllerDelegate {

    func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return CustomAnimator()
    }

}

class CustomAnimator: NSObject, UIViewControllerAnimatedTransitioning {

    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 1.0
    }


    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {

        let containerView = transitionContext.containerView
        let toViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)

        containerView.addSubview(toViewController!.view)

        toViewController!.view.alpha = 0.0

        UIView.animate(withDuration: 1.0, animations: {
            toViewController!.view.alpha = 1.0
        }, completion: { finished in
            let cancelled = transitionContext.transitionWasCancelled
            transitionContext.completeTransition(!cancelled)
        })

    }

}



UINavigationController堆栈中的Root View Controller

class SomeViewController: UIViewController, UINavigationControllerDelegate {

    func pushToNext() {
        let randomViewController = randomViewController()
        navigationController?.pushViewController(randomViewController, animated: true)
    }

}

1 个答案:

答案 0 :(得分:0)

如果要使用自定义过渡,则需要应用transitioningDelegate 将视图控制器的transitioningDelegate设置为自定义类并返回自定义动画控制器。