Swift
ViewController
iOS Development
Back Navigation
Programming Tips

Programmatically go back to previous ViewController in Swift

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Navigating between different views is an essential aspect of developing an iOS application. In Swift, moving from one ViewController to another is a standard task, and sometimes a developer may want to programmatically return to a previous ViewController. This article discusses how to achieve this in Swift, covering different scenarios, coding techniques, and common pitfalls.

Prerequisites

Before discussing programmatic navigation, it's important to understand that navigation between ViewControllers often employs a UINavigationController. This approach maintains a stack of view controllers—allowing a user to traverse back by popping a view controller off the top of the stack.

Method 1: Using popViewControllerAnimated

For apps with a UINavigationController, the current ViewController can be removed from the stack, returning to the previous ViewController using:

swift
self.navigationController?.popViewController(animated: true)
  • Explanation: popViewController(animated:) removes the topmost view controller from the navigation stack, effectively "going back."

Method 2: Using popToViewController

For more complex navigation flows, you might want to pop back to a specific ViewController in the stack:

swift
1if let viewControllers = navigationController?.viewControllers {
2    for viewController in viewControllers {
3        if let targetViewController = viewController as? TargetViewController {
4            navigationController?.popToViewController(targetViewController, animated: true)
5            break
6        }
7    }
8}
  • Explanation: Loop through the existing stack of view controllers to find the target and pop back to it.

Method 3: Using popToRootViewController

To navigate back to the root ViewController:

swift
self.navigationController?.popToRootViewController(animated: true)
  • Explanation: This returns to the root of the navigation stack.

If you are not using a UINavigationController, programmatic navigation requires different tactics:

Method 1: Using Segues

Ensure all transitions between view controllers are connected via segues in the storyboard. You can unwind a segue back to a previous screen by implementing an @IBAction method in the destination ViewController:

swift
@IBAction func unwindToPrevious(segue: UIStoryboardSegue) {
    // Actions to take when unwinding to this view controller
}
  • Create a segue in the storyboard and set the unwind action in the target ViewController.

Method 2: Creating Delegate or Notification Pattern

Building a custom navigation method using delegates or notifications allows back navigation without strictly adhering to a controller stack.

  • Implementation: Define a delegate protocol in your presenting view, with a required method for navigation. Set the delegate in the presented view and call the delegate method upon the specific action that requires back navigation.

Handling Custom Transitions

While the default transitions provided by UINavigationController are typically enough, sometimes custom animations are desired. Implementing custom transitions involves leveraging UIViewControllerAnimatedTransitioning and UIViewControllerTransitioningDelegate.

Example: Custom Back Transition

swift
1class CustomTransition: NSObject, UIViewControllerAnimatedTransitioning {
2    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
3        return 0.5
4    }
5
6    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
7        // Custom animation logic
8        let containerView = transitionContext.containerView
9        // Implement custom animation
10    }
11}
  • Explanation: This class provides a duration and custom animation logic, which can be applied when a ViewController is dismissed or popped.

Summary Table

MethodUse CaseDescription
popViewControllerAnimatedStandard backward navigationPops the current ViewController from the stack, animated or non-animated.
popToViewControllerSpecific target navigationPops to a specific ViewController designated in the navigation stack.
popToRootViewControllerReturn to app's main screenClears intermediary controllers, returning to root.
Segue & UnwindNavigation in storyboard setupsUses storyboard segue unwinding for backward transitions.
Delegate or NotificationNon-stack-based navigationCustom navigation for controllers outside a strict stack hierarchy.
Custom TransitionVisual enhancement during navigationImplements and design custom animations during view transitions.

Conclusion

Programmatically going back in a view hierarchy within iOS applications requires an understanding of the navigation stack, and Swift provides numerous ways to achieve this. Whether using the default UINavigationController, storyboards, or custom delegate patterns, carefully considering the structure of your app and the desired user experience will guide the decision on which approach to use. Remember to manage memory and performance implications to efficiently use resources—especially when managing large navigation stacks or custom animations.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.