Swift

Programmatically go back to previous ViewController in Swift

19 September 2026 · 10 min read

Programmatically go back to previous ViewController in Swift

Navigating between ViewControllers is a fundamental aspect of iOS app development using Swift. Whether you’re building a simple app or a complex application, understanding how to programmatically go back to the previous ViewController is crucial for creating a seamless user experience. The ability to control the navigation flow allows you to guide users through your app in a logical and intuitive manner. This blog post will delve into the various methods for achieving this, providing clear explanations, code examples, and best practices. We’ll explore techniques using UINavigationController, custom segues, and even handling scenarios without a navigation stack. By the end, you’ll have a comprehensive understanding of how to programmatically manage your ViewController navigation in Swift.

Understanding Navigation Controllers and View Controller Stacks

The UINavigationController is a cornerstone of iOS navigation. It manages a stack of ViewControllers, allowing users to move forward and backward through the app’s hierarchy. Think of it like a stack of cards, where the top card is the currently visible ViewController. When you push a new ViewController onto the stack, it becomes the new top card. Going back to the previous ViewController involves popping the current ViewController off the stack. This is a common pattern for hierarchical navigation, providing a clear and predictable user experience. It’s important to understand how the navigation stack works to effectively manage the flow of your application.

To programmatically go back to the previous ViewController using a UINavigationController, you typically use the popViewController(animated:) method. This method removes the top ViewController from the navigation stack and animates the transition back to the previous one. For example: self.navigationController?.popViewController(animated: true). The animated parameter controls whether the transition is animated or not. Using animation provides a visual cue to the user, making the navigation feel more natural. Another option is to use popToRootViewController(animated:), which navigates all the way back to the root ViewController of the navigation stack. This is useful when you want to quickly return the user to the starting point of a particular flow within your app.

There are scenarios where you might want to go back to a specific ViewController in the stack, not just the immediate previous one. In such cases, you can use the popToViewController(_:animated:) method. This method requires you to provide the specific ViewController instance you want to navigate back to. You’ll need to iterate through the navigationController?.viewControllers array to find the desired ViewController. Once you have the instance, you can call popToViewController(_:animated:) to navigate back to it. This offers more granular control over the navigation flow, allowing you to create complex navigation patterns within your app.

Using popViewController(animated:) for Simple Back Navigation

The simplest way to programmatically go back to the previous ViewController is by using the popViewController(animated:) method of the UINavigationController. This method is straightforward and effective for most common navigation scenarios. It simply removes the current ViewController from the navigation stack, revealing the ViewController that was previously on top. This provides a clear and intuitive way for users to navigate backward through your app.

Here’s a code snippet demonstrating how to use popViewController(animated:): swift if let navigationController = self.navigationController { navigationController.popViewController(animated: true) } else { // Handle the case where there is no navigation controller print(“Not embedded in a navigation controller.”) } This code first checks if the current ViewController is embedded in a UINavigationController. If it is, it calls popViewController(animated: true) to navigate back to the previous ViewController with animation. If not, it prints a message to the console, indicating that the ViewController is not part of a navigation stack. It’s important to handle this case to prevent unexpected behavior or crashes in your app. According to Apple’s documentation, always ensure a navigation controller exists before attempting to pop a view controller. Apple Documentation

One common mistake developers make is assuming that a ViewController is always embedded in a UINavigationController. This can lead to crashes if the ViewController is presented modally or is not part of a navigation stack. To avoid this, always check if self.navigationController is not nil before calling popViewController(animated:). You can also use optional chaining to simplify the code: self.navigationController?.popViewController(animated: true). This will safely call popViewController(animated:) only if self.navigationController is not nil. This is a best practice to ensure your app is robust and handles different navigation scenarios gracefully.

Sometimes, you might need to navigate back to a specific ViewController in the navigation stack, not just the immediate previous one. This can be useful in scenarios where you want to skip several steps in the navigation hierarchy or return to a particular point in the user flow. The popToViewController(_:animated:) method of the UINavigationController allows you to achieve this. However, it requires you to have a reference to the specific ViewController instance you want to navigate back to.

Here’s an example of how to use popToViewController(_:animated:): swift if let navigationController = self.navigationController { for viewController in navigationController.viewControllers { if let targetViewController = viewController as? MyTargetViewController { navigationController.popToViewController(targetViewController, animated: true) return } } // Handle the case where the target view controller is not found print(“Target view controller not found in the navigation stack.”) } else { // Handle the case where there is no navigation controller print(“Not embedded in a navigation controller.”) } This code iterates through the navigationController.viewControllers array to find a ViewController of type MyTargetViewController. Once it finds the target ViewController, it calls popToViewController(_:animated:) to navigate back to it. If the target ViewController is not found, it prints a message to the console. This is a more complex approach than simply popping the previous ViewController, but it offers greater flexibility in controlling the navigation flow.

Featured Snippet:
To navigate to a specific ViewController, iterate through the navigationController.viewControllers array. Check if each ViewController is of the desired type. If it is, use navigationController.popToViewController(targetViewController, animated: true) to go back to it. Ensure you handle cases where the target ViewController isn’t found to avoid errors. This method provides precise control over navigation within your app.

Handling Navigation Without a Navigation Controller

While UINavigationController is the standard way to manage navigation in iOS apps, there are situations where you might need to navigate back to a previous ViewController without using a navigation controller. This can occur when a ViewController is presented modally or when you’re using a custom navigation implementation. In these cases, you’ll need to use alternative methods to dismiss the current ViewController and return to the previous one.

If a ViewController is presented modally, you can dismiss it using the dismiss(animated:completion:) method. This method dismisses the current ViewController and returns to the ViewController that presented it. For example: self.dismiss(animated: true, completion: nil). The animated parameter controls whether the dismissal is animated or not. The completion parameter allows you to execute code after the dismissal is complete. This is a simple and effective way to handle navigation when using modal presentations. According to a Stack Overflow survey, modal presentations are commonly used for temporary views like settings or forms. Stack Overflow

In scenarios where you’re using a custom navigation implementation, you’ll need to manage the navigation stack manually. This typically involves keeping track of the ViewControllers in an array and using custom transitions to animate between them. When you want to go back to the previous ViewController, you’ll need to remove the current ViewController from the array and present the previous one. This approach requires more code and careful management, but it offers the greatest flexibility in customizing the navigation flow. However, keep in mind that you’re essentially re-inventing features already provided by UINavigationController, so it’s important to weigh the benefits against the added complexity. Consider using established libraries or design patterns to simplify this process. Consider using a custom navigation bar.

Infographic here
- Use `popViewController(animated:)` for simple back navigation within a `UINavigationController`. - Use `popToViewController(_:animated:)` to navigate to a specific view controller in the navigation stack.
  1. Check if the current view controller is embedded in a UINavigationController.
  2. If so, use navigationController?.popViewController(animated: true) to go back.
  3. If not, consider using dismiss(animated:completion:) if presented modally.

Best Practices for View Controller Navigation in Swift

Effective ViewController navigation is crucial for creating a user-friendly iOS app. Following best practices ensures a smooth and intuitive experience for your users. This includes consistent navigation patterns, clear visual cues, and proper error handling. By adhering to these guidelines, you can create an app that is easy to navigate and enjoyable to use.

One important best practice is to use a consistent navigation pattern throughout your app. This means using the same types of transitions, animations, and button styles for navigation. Consistency helps users learn how to navigate your app quickly and easily. For example, always use the standard back button in the UINavigationController for hierarchical navigation. Avoid using custom back buttons unless absolutely necessary, as they can confuse users. According to Nielsen Norman Group, consistency is a key principle of usability. Nielsen Norman Group

  • Ensure consistent navigation patterns throughout the app.
  • Handle cases where a UINavigationController might not be present.

Another best practice is to handle cases where a UINavigationController might not be present. As mentioned earlier, it’s important to check if self.navigationController is not nil before calling navigation methods. This prevents crashes and ensures your app handles different navigation scenarios gracefully. You should also provide clear error messages or alternative navigation options if the user attempts to navigate back when there is no previous ViewController. This can be achieved by disabling back buttons or displaying an alert message. Remember that user experience is key, and thoughtful error handling contributes significantly to a positive experience.

Finally, consider using a state management system to track the navigation history of your app. This can be especially useful in complex apps with multiple navigation flows. A state management system allows you to easily navigate back to any point in the user’s journey, even if the navigation stack has been modified. Popular state management solutions like Redux or SwiftUI’s Environment can help manage complex app states effectively.

FAQ Section:

How do I programmatically go back to the previous ViewController in Swift?
Use `self.navigationController?.popViewController(animated: true)` if you are using a `UINavigationController`.
What if I'm not using a `UINavigationController`?
If the ViewController was presented modally, use `self.dismiss(animated: true, completion: nil)`.
How can I go back to a specific ViewController in the stack?
Iterate through `navigationController?.viewControllers` and use `navigationController?.popToViewController(_:animated:)` when you find the target.
Is it necessary to animate the transition?
Animating the transition provides a smoother user experience but it's optional. Set `animated: false` for an instant transition.
We've covered a range of methods to programmatically navigate back to previous ViewControllers in Swift, from simple popViewController calls to more complex scenarios involving custom navigation stacks and modal presentations. The key takeaway is to understand the context in which your ViewControllers are presented and choose the appropriate method for navigation. By implementing these techniques and following best practices, you can create a seamless and intuitive user experience. Now, why not experiment with these techniques in your own projects? Consider exploring custom transitions for enhanced visual appeal or integrating a state management system for more complex navigation scenarios. Your users will appreciate the effort you put into creating a well-navigated and enjoyable app. **Question & Answer :** I send the user over to a page on a button click. This page is a **UITableViewController**.

Now if the user taps on a cell, I would like to push him back to the previous page.

I thought about something like self.performSegue("back").... but this seems to be a bad idea.

What is the correct way to do it?

Swift 3:

If you want to go back to the previous view controller

_ = navigationController?.popViewController(animated: true) 

If you want to go back to the root view controller

_ = navigationController?.popToRootViewController(animated: true) 

If you are not using a navigation controller then pls use the below code.

self.dismiss(animated: true, completion: nil) 

animation value you can set according to your requirement.