Bird
Raised Fist0
iOS Swiftmobile~20 mins

Programmatic navigation in iOS Swift - Mini App: Build & Ship

Choose your learning style10 modes available
Build: Home Screen
This screen shows a button that, when tapped, navigates programmatically to a Detail Screen.
Target UI
-------------------
|     Home Screen  |
|                  |
|  [Go to Details] |
|                  |
-------------------
Add a button labeled 'Go to Details' on the Home Screen
When the button is tapped, navigate programmatically to a Detail Screen
The Detail Screen should show a label with text 'Detail Screen'
Use UIKit and UINavigationController for navigation
Starter Code
iOS Swift
import UIKit

class HomeViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        // TODO: Add button and navigation code here
    }
}

class DetailViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        // TODO: Add label here
    }
}

@main
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        window = UIWindow(frame: UIScreen.main.bounds)
        let navController = UINavigationController(rootViewController: HomeViewController())
        window?.rootViewController = navController
        window?.makeKeyAndVisible()
        return true
    }
}
Task 1
Task 2
Task 3
Solution
iOS Swift
import UIKit

class HomeViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white

        let button = UIButton(type: .system)
        button.setTitle("Go to Details", for: .normal)
        button.translatesAutoresizingMaskIntoConstraints = false
        button.addTarget(self, action: #selector(goToDetails), for: .touchUpInside)
        view.addSubview(button)

        NSLayoutConstraint.activate([
            button.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            button.centerYAnchor.constraint(equalTo: view.centerYAnchor)
        ])
    }

    @objc func goToDetails() {
        let detailVC = DetailViewController()
        navigationController?.pushViewController(detailVC, animated: true)
    }
}

class DetailViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white

        let label = UILabel()
        label.text = "Detail Screen"
        label.font = UIFont.systemFont(ofSize: 24, weight: .medium)
        label.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(label)

        NSLayoutConstraint.activate([
            label.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            label.centerYAnchor.constraint(equalTo: view.centerYAnchor)
        ])
    }
}

@main
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        window = UIWindow(frame: UIScreen.main.bounds)
        let navController = UINavigationController(rootViewController: HomeViewController())
        window?.rootViewController = navController
        window?.makeKeyAndVisible()
        return true
    }
}

We create a UIButton in HomeViewController and center it using Auto Layout. The button's title is set to 'Go to Details'. We add a target action goToDetails that is called when the button is tapped.

In goToDetails, we create an instance of DetailViewController and push it onto the navigation stack using navigationController?.pushViewController. This performs the programmatic navigation.

The DetailViewController shows a centered UILabel with the text 'Detail Screen'.

The app uses a UINavigationController as the root controller to enable navigation.

Final Result
Completed Screen
-------------------
|     Home Screen  |
|                  |
|  [Go to Details] |
|                  |
-------------------

--tap button-->

-------------------
|    Detail Screen |
|                  |
|   Detail Screen  |
|                  |
-------------------
User taps 'Go to Details' button on Home Screen
App navigates to Detail Screen with label 'Detail Screen'
User can swipe back or tap back button to return to Home Screen
Stretch Goal
Add a 'Back to Home' button on the Detail Screen that navigates back programmatically
💡 Hint
Add a UIButton on DetailViewController and call navigationController?.popViewController(animated: true) when tapped

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