Execute action when back bar button of UINavigationController is pressed
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Navigating through applications on iOS often involves moving forward and backward through a hierarchy of view controllers using a `UINavigationController`. The back bar button, which is a critical component of the `UINavigationController`, is used to navigate back to the previous view in the hierarchy. In some cases, you may want to perform certain actions when this back button is pressed. This article delves into this scenario, providing insights and technical guidance on how to implement and manage this behavior effectively.
Understanding the UINavigationController's Back Button
The back button in a `UINavigationController` typically appears after a `UIViewController` has been pushed onto the navigation stack. This button is automatically created and managed by the navigation controller, which handles the pop operation to remove the current view from the stack and return to the previous view. However, `UINavigationController` does not provide a direct way to intercept the back button press. Instead, developers must implement custom logic to execute actions during this interaction.
Intercepting the Back Button Press
Option 1: Using `UIViewController` Lifecycle Methods
One of the simplest ways to detect when a view is about to be popped is by utilizing the `viewWillDisappear(_:)` method. This method is called just before the view is removed from the screen.
- `isMovingFromParent`: This Boolean property returns `true` if the view controller is being removed from its parent. In the context of a back button press, it helps confirm that the disappearance is due to a navigation back action.
- By using a custom `UIBarButtonItem`, you gain the ability to directly handle the button press and perform any necessary actions before executing the default back behavior.
- Navigation Guards: Implement navigation logic that determines if the navigation should proceed based on application state or user input.
- User Experience (UX): Ensure that any additional actions do not hinder the user's navigation experience, possibly using animations or transitions for better flow.
- Back Stack Management: Be aware of the complete navigation stack if implementing conditional logic based on multiple back navigations.

