iOS how to detect programmatically when top view controller is popped?

后端 未结 10 1361
逝去的感伤
逝去的感伤 2020-12-04 17:32

Suppose I have a nav controller stack with 2 view controllers: VC2 is on top and VC1 is underneath. Is there code I can include in VC1 that will detect that VC2 has just be

10条回答
  •  孤街浪徒
    2020-12-04 18:16

    I got the same situation but with slight more specific use case. In my case we wanted to determine if a VC1 is appeared/displayed when user tap on VC2's back button where VC2 is pushed on navigationController over VC1.

    So I used help of snarshad's answer to customised as per my need. Here is the code in VC1's viewDidAppear in swift 3.

    // VC1: ParentViewController
    // VC2: ChildViewController
    
        override func viewDidAppear(_ animated: Bool) {
            super.viewDidAppear(animated)
    
            if let transitionCoordinator = navigationController?.transitionCoordinator,
                let fromVC = transitionCoordinator.viewController(forKey: UITransitionContextViewControllerKey.from),
                let toVC = transitionCoordinator.viewController(forKey: UITransitionContextViewControllerKey.to),
                fromVC is ChildViewController,
                toVC is ParentViewController {
    
                print("Back button pressed on ChildViewController, and as a result ParentViewController appeared")
            }
        }
    

提交回复
热议问题