我应该在哪里设置UINavigationController的委托属性?

时间:2017-06-04 23:16:22

标签: ios swift uiviewcontroller uinavigationcontroller

我正在使用一些自定义控制器转换,它们使用UINavigationController的delegate属性。如果我在viewDidLoad()中设置它,self.navigationController?.delegate会在推送后的某个时刻解除分配。在viewWillAppear()中设置它有效,但我想知道为什么该属性首先被解除分配,以及人们通常设置此属性的位置。

    // The first time you push, it will work correctly, and the delegate function below is called. After you pop back to this controller, delegate is nil (has been deallocated)
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationController?.delegate = self
    }

    // Brute force works
    override func viewWillAppear(_ animated: Bool) {
        self.navigationController?.delegate = self
    }

    func navigationController(_ navigationController: UINavigationController,
                              animationControllerFor operation: UINavigationControllerOperation,
                              from fromVC: UIViewController,
                              to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning?
    {
        if operation == .push {
            return WTPPushAnimator()
        }
        if operation == .pop {
            return WTPPopAnimator()
        }
        return nil;
    }

1 个答案:

答案 0 :(得分:0)

如果您推送的ViewController也设置了navigationController?.delegate = self,那么当弹出ViewController时,ViewController将被取消分配,weak var delegate将会被释放设为nilviewDidLoad()仅在首次创建ViewController时运行,因此当返回到第一个ViewController时,viewDidLoad()将无法再次运行。在推送viewWillAppear()或在弹出广告时返回时,始终会调用ViewController,因此viewWillAppear()是设置此delegate的正确位置。