问题
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