How to detect if view controller is being popped of from the navigation controller?

前端 未结 5 1109
野的像风
野的像风 2020-12-24 00:52

I currently need to implement some code when the top view controller is being popped off from my navigation controller. Is there a way to detect when the view controller is

5条回答
  •  盖世英雄少女心
    2020-12-24 01:39

    My experience with iOS 13 is that the property value of isMovingFromParent is not always consistent. When you have search controller being in active mode (search text field is tapped), back to parent view will have false value for this property.

    Here is my way to determine if a view is from parent or not:

    class MyBaseViewController: UIViewController {
        private var _isPushedToAnotherView = false
        var isPushedToAnotherView: Bool {
          return _isPushedToAnotherView
        }
        override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
          super.prepare(for: segue, sender: sender)
          ...
          _isPushedToAnotherView = true
        }
        override func viewWillAppear(_ animated: Bool) {
          super.viewWillAppear(animated)
          ...
          _isPushedToAnotherView = false
        }
        ...
    }
    
    class MyExtendedClass: MyBaseViewController {
      ...
      override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        ...
        if !isPushedToAnotherView {
            // clear resources hold by this class
        }
    }
    

提交回复
热议问题