Execute action when back bar button of UINavigationController is pressed

Matheus Mello
Matheus Mello
September 2, 2023
Cover Image for Execute action when back bar button of UINavigationController is pressed

How to Execute an Action When the Back Bar Button of a UINavigationController is Pressed in Swift πŸ”„

Have you ever needed to perform a specific action when the back button of a UINavigationController is pressed in your iOS app? Maybe you want to clear some data or update a view before navigating back to the previous screen. In this blog post, we'll explore a common issue developers face and provide easy solutions to execute an action when the back button is pressed. Let's dive in! πŸ’ͺ

The Challenge: Executing an Action While Navigating Back πŸ€”

The UINavigationController in iOS provides a built-in back button that pops the top view controller from the navigation stack and returns to the previous screen. However, by default, there is no straightforward way to execute custom code when the back button is pressed.

Here's an example scenario: let's say you have a UINavigationController with multiple view controllers stacked on top of each other. When the user taps the back button, you want to empty an array used by the current view controller.

Solution: Method Swizzling to the Rescue! πŸ¦Έβ€β™€οΈ

One way to tackle this issue is by utilizing method swizzling, a technique in which you exchange the implementation of a method with a new one at runtime. By doing so, we can intercept the back button press event and execute our custom code before the default navigation behavior takes place.

Here's how you can implement this approach in Swift:

extension UINavigationController {
    
    private static let swizzleMethod: Void = {
        let originalSelector = #selector(UINavigationController.viewWillDisappear(_:))
        let swizzledSelector = #selector(UINavigationController.customViewWillDisappear(_:))
        
        let originalMethod = class_getInstanceMethod(UINavigationController.self, originalSelector)
        let swizzledMethod = class_getInstanceMethod(UINavigationController.self, swizzledSelector)
        
        method_exchangeImplementations(originalMethod!, swizzledMethod!)
    }()
    
    @objc private func customViewWillDisappear(_ animated: Bool) {
        // Add your custom code here
        // Perform the action you want before navigating back
        
        // Call the original implementation
        customViewWillDisappear(animated)
    }
    
    open override func viewDidLoad() {
        super.viewDidLoad()
        UIViewController.initializeSwizzleMethod
    }
    
}

With this extension added to your project, any UINavigationController in your app will automatically swizzle the viewWillDisappear method to our custom implementation, allowing us to execute additional code upon the back button press.

Example Usage: Emptying an Array When Navigating Back πŸ—‘οΈ

To make things more tangible, let's see an example of how you can use the solution described above to empty an array when navigating back.

Assuming you have a view controller class called MyViewController that manages the array you want to empty, you can override the viewWillDisappear method in MyViewController like so:

class MyViewController: UIViewController {
    
    var myArray: [Any] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Configure your view controller as needed
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        // Perform your custom action here
        myArray.removeAll()
    }
    
}

By overriding viewWillDisappear in MyViewController, you can safely perform any necessary clean-up operations, such as emptying the array, before the view controller is popped from the navigation stack.

Go Ahead and Customize Your UINavigationController! 🎨

Now that you have a clear solution to executing actions when the back button of a UINavigationController is pressed, feel free to customize your navigation flow to fit your app's needs. Whether you need to update views, clear data, or trigger specific actions, you now have the power to do so!

Share your experience with us! Have you faced similar challenges when working with UINavigationController, or do you have other tips to share? Let us know in the comments below. Happy coding! πŸš€

Take Your Tech Career to the Next Level

Our application tracking tool helps you manage your job search effectively. Stay organized, track your progress, and land your dream tech job faster.

Your Product
Product promotion

Share this article

More Articles You Might Like

Latest Articles

Cover Image for How can I echo a newline in a batch file?
batch-filenewlinewindows

How can I echo a newline in a batch file?

Published on March 20, 2060

πŸ”₯ πŸ’» πŸ†’ Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Cover Image for How do I run Redis on Windows?
rediswindows

How do I run Redis on Windows?

Published on March 19, 2060

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! πŸš€ Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Cover Image for Best way to strip punctuation from a string
punctuationpythonstring

Best way to strip punctuation from a string

Published on November 1, 2057

# The Art of Stripping Punctuation: Simplifying Your Strings πŸ’₯βœ‚οΈ Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Cover Image for Purge or recreate a Ruby on Rails database
rakeruby-on-railsruby-on-rails-3

Purge or recreate a Ruby on Rails database

Published on November 27, 2032

# Purge or Recreate a Ruby on Rails Database: A Simple Guide πŸš€ So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? πŸ€” Well, my