Execute action when back bar button of UINavigationController is pressed

Cover Image for Execute action when back bar button of UINavigationController is pressed
Matheus Mello
Matheus Mello
published a few days ago. updated a few hours ago

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! πŸš€


More Stories

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

How can I echo a newline in a batch file?

updated a few hours ago
batch-filenewlinewindows

πŸ”₯ πŸ’» πŸ†’ 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

Matheus Mello
Matheus Mello
Cover Image for How do I run Redis on Windows?

How do I run Redis on Windows?

updated a few hours ago
rediswindows

# 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

Matheus Mello
Matheus Mello
Cover Image for Best way to strip punctuation from a string

Best way to strip punctuation from a string

updated a few hours ago
punctuationpythonstring

# 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

Matheus Mello
Matheus Mello
Cover Image for Purge or recreate a Ruby on Rails database

Purge or recreate a Ruby on Rails database

updated a few hours ago
rakeruby-on-railsruby-on-rails-3

# 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

Matheus Mello
Matheus Mello