Detecting when the 'back' button is pressed on a navbar

user440096 picture user440096 · Nov 22, 2011 · Viewed 138.2k times · Source

I need to perform some actions when the back button(return to previous screen, return to parent-view) button is pressed on a Navbar.

Is there some method I can implement to catch the event and fire off some actions to pause and save data before the screen disappears?

Answer

elitalon picture elitalon · Jan 4, 2013

UPDATE: According to some comments, the solution in the original answer does not seem to work under certain scenarios in iOS 8+. I can't verify that that is actually the case without further details.

For those of you however in that situation there's an alternative. Detecting when a view controller is being popped is possible by overriding willMove(toParentViewController:). The basic idea is that a view controller is being popped when parent is nil.

Check out "Implementing a Container View Controller" for further details.


Since iOS 5 I've found that the easiest way of dealing with this situation is using the new method - (BOOL)isMovingFromParentViewController:

- (void)viewWillDisappear:(BOOL)animated {
  [super viewWillDisappear:animated];

  if (self.isMovingFromParentViewController) {
    // Do your stuff here
  }
}

- (BOOL)isMovingFromParentViewController makes sense when you are pushing and popping controllers in a navigation stack.

However, if you are presenting modal view controllers you should use - (BOOL)isBeingDismissed instead:

- (void)viewWillDisappear:(BOOL)animated {
  [super viewWillDisappear:animated];

  if (self.isBeingDismissed) {
    // Do your stuff here
  }
}

As noted in this question, you could combine both properties:

- (void)viewWillDisappear:(BOOL)animated {
  [super viewWillDisappear:animated];

  if (self.isMovingFromParentViewController || self.isBeingDismissed) {
    // Do your stuff here
  }
}

Other solutions rely on the existence of a UINavigationBar. Instead like my approach more because it decouples the required tasks to perform from the action that triggered the event, i.e. pressing a back button.