Where should I set UINavigationController's delegate property?

三世轮回 提交于 2020-04-11 12:08:29

问题


I'm working with some custom controller transitions, which make use of UINavigationController's delegate property. If I set it in viewDidLoad(), self.navigationController?.delegate gets deallocated at some point after the push. Setting it in viewWillAppear() works, but I'm wondering why that property gets deallocated in the first place, and where people typically set this property.

    // 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:


If the ViewController you are pushing also sets navigationController?.delegate = self, then when that ViewController is popped, that ViewController will be deallocated and the weak var delegate will be set to nil. viewDidLoad() only runs when the ViewController is first created, so when returning to the first ViewController, viewDidLoad() will not run again. viewWillAppear() is always called when a ViewController is pushed or when it is returned to on a pop, so viewWillAppear() is the right place to set this delegate.



来源:https://stackoverflow.com/questions/44359723/where-should-i-set-uinavigationcontrollers-delegate-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!