简体   繁体   中英

How to call a method when an iOS UINavigationController has been popped?

I have an iOS UINavigationController whose rootViewController is ViewController1 . ViewController1 pushes ViewController2 by calling pushViewController(_:animated:) , and then ViewController2 pops itself by calling popViewController(animated:) . I am not using a storyboard.

Now that I have arrived back in ViewController1 , I would like ViewController1 to do something automatically.

How can I arrange to have a method of ViewController1 called when we have returned there from ViewController2 ? In other words, how can ViewController1 sense that it has just been uncovered? I know I can do this by calling the navigationController(_:didShow:animated:) method of a UINavigationControllerDelegate , but is there a simpler way?

You can create a protocol that lets you notify ViewController1 when ViewController2 is dismissed, somewhat like this:

protocol FeedbackDelegate: class {
    func shouldDoSomething()
}

class ViewController1: UIViewController, FeedbackDelegate {
    func thisIsWhereYouPresentVC2() {
        let vc = ViewController2()
        vc.feedbackDelegate = self
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    // MARK: - FeedbackDelegate
    func shouldDoSomething() {
    }
}

class ViewController2: UIViewController {
    weak var feedbackDelegate: FeedbackDelegate?
    
    func thisIsWhereYouDismissVC2() {
        self.feedbackDelegate?.shouldDoSomething()
        self.navigationController?.popViewController(animated: true)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM