Bird
Raised Fist0
iOS Swiftmobile~5 mins

Programmatic navigation in iOS Swift

Choose your learning style10 modes available
Introduction

Programmatic navigation lets your app move between screens by code, not just by tapping buttons in the design. This helps you control where users go based on what they do.

When you want to go to a new screen after a user action like a button tap.
When you need to move back to a previous screen automatically.
When you want to pass data to the next screen before showing it.
When navigation depends on some logic, like login success.
When you want to open a screen without using storyboard segues.
Syntax
iOS Swift
let nextVC = NextViewController()
navigationController?.pushViewController(nextVC, animated: true)

// To go back:
navigationController?.popViewController(animated: true)

Use pushViewController to go forward in the navigation stack.

Use popViewController to go back to the previous screen.

Examples
This pushes a new DetailViewController onto the navigation stack, showing the detail screen.
iOS Swift
let detailVC = DetailViewController()
navigationController?.pushViewController(detailVC, animated: true)
This goes back to the previous screen in the navigation stack.
iOS Swift
navigationController?.popViewController(animated: true)
Here, we create a ProfileViewController, set a user ID, then navigate to it.
iOS Swift
let profileVC = ProfileViewController()
profileVC.userId = 123
navigationController?.pushViewController(profileVC, animated: true)
Sample App

This app starts with a white screen and a button labeled "Go to Second Screen". When tapped, it moves to a gray screen with a "Go Back" button. Tapping "Go Back" returns to the first screen.

iOS Swift
import UIKit

class FirstViewController: UIViewController {
  override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = .white
    let button = UIButton(type: .system)
    button.setTitle("Go to Second Screen", for: .normal)
    button.addTarget(self, action: #selector(goToSecond), for: .touchUpInside)
    button.frame = CGRect(x: 50, y: 200, width: 220, height: 50)
    view.addSubview(button)
  }

  @objc func goToSecond() {
    let secondVC = SecondViewController()
    navigationController?.pushViewController(secondVC, animated: true)
  }
}

class SecondViewController: UIViewController {
  override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = .lightGray
    let button = UIButton(type: .system)
    button.setTitle("Go Back", for: .normal)
    button.addTarget(self, action: #selector(goBack), for: .touchUpInside)
    button.frame = CGRect(x: 50, y: 200, width: 220, height: 50)
    view.addSubview(button)
  }

  @objc func goBack() {
    navigationController?.popViewController(animated: true)
  }
}

// In AppDelegate or SceneDelegate, set FirstViewController as root inside UINavigationController
OutputSuccess
Important Notes

Make sure your view controller is inside a UINavigationController to use push/pop navigation.

You can pass data to the next screen by setting properties before pushing it.

Animated transitions make navigation feel smooth and natural.

Summary

Programmatic navigation moves between screens using code.

Use pushViewController to go forward and popViewController to go back.

It helps control app flow based on user actions or logic.

Practice

(1/5)
1. What does pushViewController do in iOS programmatic navigation?
easy
A. It moves to a new screen by adding it on top of the navigation stack.
B. It removes the current screen from the navigation stack.
C. It resets the entire navigation stack to the root screen.
D. It presents a screen modally without navigation.

Solution

  1. Step 1: Understand navigation stack behavior

    In iOS, navigation uses a stack where screens are pushed and popped.
  2. Step 2: Role of pushViewController

    The method pushViewController adds a new screen on top, moving forward.
  3. Final Answer:

    It moves to a new screen by adding it on top of the navigation stack. -> Option A
  4. Quick Check:

    pushViewController = move forward [OK]
Hint: Push adds a screen on top; pop removes the top screen [OK]
Common Mistakes:
  • Confusing push with pop behavior
  • Thinking push resets the stack
  • Mixing modal presentation with push navigation
2. Which of the following is the correct syntax to push a view controller named DetailViewController onto the navigation stack?
easy
A. navigationController.pushViewController(DetailViewController, animated: true)
B. navigationController?.pushViewController(DetailViewController(), animated: true)
C. navigationController.push(DetailViewController(), animated: true)
D. navigationController?.pushViewController(DetailViewController, animated: false)

Solution

  1. Step 1: Check method call and optional chaining

    navigationController is optional, so use ? to safely call method.
  2. Step 2: Instantiate the view controller correctly

    Use DetailViewController() to create an instance before pushing.
  3. Final Answer:

    navigationController?.pushViewController(DetailViewController(), animated: true) -> Option B
  4. Quick Check:

    Optional chaining + instance creation = correct syntax [OK]
Hint: Use ? for optional navigationController and () to create instance [OK]
Common Mistakes:
  • Forgetting to instantiate the view controller
  • Not using optional chaining on navigationController
  • Using wrong method name like push instead of pushViewController
3. Given this code snippet, what will happen when the button is tapped?
func buttonTapped() {
  let vc = SettingsViewController()
  navigationController?.pushViewController(vc, animated: true)
}
medium
A. The app will crash because SettingsViewController is not initialized properly.
B. Nothing will happen because pushViewController is called without a navigation controller.
C. The current screen will be removed and replaced by SettingsViewController.
D. The app will navigate to the SettingsViewController screen with animation.

Solution

  1. Step 1: Analyze the code behavior

    The code creates a new SettingsViewController instance and pushes it onto the navigation stack.
  2. Step 2: Understand navigationController optional chaining

    If navigationController exists, it will push with animation, moving to the new screen.
  3. Final Answer:

    The app will navigate to the SettingsViewController screen with animation. -> Option D
  4. Quick Check:

    pushViewController with valid instance = navigate forward [OK]
Hint: pushViewController moves forward if navigationController exists [OK]
Common Mistakes:
  • Assuming crash without checking optional navigationController
  • Thinking push removes current screen
  • Confusing push with modal presentation
4. Identify the error in this code snippet for navigating back to the previous screen:
func goBack() {
  navigationController.popViewController(animated: true)
}
medium
A. popViewController is not a valid method for navigationController.
B. popViewController should be called with a completion handler.
C. Missing optional chaining operator (?) after navigationController.
D. Missing parentheses after navigationController to call optional chaining.

Solution

  1. Step 1: Check navigationController usage

    navigationController is optional, so it needs optional chaining with ? before calling methods.
  2. Step 2: Identify missing ? operator

    The code uses navigationController.popViewController without ?, causing a compile error.
  3. Final Answer:

    Missing optional chaining operator (?) after navigationController. -> Option C
  4. Quick Check:

    Optional chaining needed for navigationController calls [OK]
Hint: Use ? after navigationController to safely call methods [OK]
Common Mistakes:
  • Forgetting navigationController is optional
  • Trying to add completion handler to popViewController
  • Confusing popViewController with pushViewController
5. You want to programmatically navigate back to the root view controller from a deep screen. Which code snippet correctly achieves this?
hard
A. navigationController?.popToRootViewController(animated: true)
B. navigationController?.popViewController(animated: true)
C. navigationController?.dismiss(animated: true)
D. navigationController?.pushViewController(rootViewController, animated: true)

Solution

  1. Step 1: Understand navigation stack methods

    popToRootViewController moves back to the first screen in the stack, popping all intermediate ones.
  2. Step 2: Compare options

    popViewController removes only the top screen; dismiss is for modal; push adds a new screen, not back.
  3. Final Answer:

    navigationController?.popToRootViewController(animated: true) -> Option A
  4. Quick Check:

    popToRootViewController = go back to root [OK]
Hint: Use popToRootViewController to return to first screen [OK]
Common Mistakes:
  • Using popViewController to go back multiple screens
  • Confusing dismiss with navigation pop
  • Trying to push root instead of popping to it
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard