当我们执行segue时,很容易获得目标视图控制器,因此我们可以使用prepare(for:(方法将数据传递给它。
当按下导航控制器的后退按钮时,我想知道正确的方法。
我已经设法拼凑出了一些有效的东西,但使用我对导航控制器中视图控制器层次结构的了解,而不是动态获取目的地,感觉是错误的。也许我想得太多了?
override func willMove(toParent parent: UIViewController?) {
super.willMove(toParent: parent)
// This method is called more than once - parent is only nil when back button is pressed
if (parent == nil) {
guard let destination = self.navigationController?.viewControllers.first as? MyTableViewController else {
return
}
print("destination is (destination)")
// set delegate of my networking class to destination here
// call async method on networking class to retrieve updated data for my table view
}
}
一般来说,尝试这样做会导致耦合过于紧密。你正在远离的VC不需要知道它的去向。
最好在MyTableViewController
类中的viewWillAppear
或viewDidAppear
中实现networking class
方法。
然而,您可以尝试一下:
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// make sure we're in a navigation controller
guard let navC = navigationController else { return }
if navC.viewControllers.firstIndex(of: self) != nil {
// we're still in the nav stack, so we've either
// pushed to another VC, or presented a full-screen VC
// (or maybe something else)
return
}
// we've been removed from the nav stack
// so user tapped Back button
print("back button tapped")
// see if we're navigating back to an instance of MyTableViewController
guard let destVC = navC.viewControllers.last as? MyTableViewController else {
return
}
// do something with destVC...
print("on our way to", destVC)
}
注意:我只是举个例子。。。它将需要大量的测试,并可能需要额外的案例处理。