Bird
0
0

Consider this Swift code inside a view controller:

medium📝 Predict Output Q4 of 15
iOS Swift - Navigation
Consider this Swift code inside a view controller:
let detailVC = UIViewController()
detailVC.view.backgroundColor = .red
navigationController?.pushViewController(detailVC, animated: true)
What is the expected behavior when this code executes?
AThe app will crash because the view controller is not initialized properly.
BThe current view controller is replaced without animation.
CA new view controller with a red background is pushed onto the navigation stack and displayed.
DNothing happens because pushViewController is not called correctly.
Step-by-Step Solution
Solution:
  1. Step 1: Create a new UIViewController instance

    The code initializes a new UIViewController named detailVC and sets its background color to red.
  2. Step 2: Push the new view controller

    Calling navigationController?.pushViewController(detailVC, animated: true) adds detailVC to the navigation stack and animates the transition.
  3. Final Answer:

    A new view controller with a red background is pushed onto the navigation stack and displayed. -> Option C
  4. Quick Check:

    Check if navigationController is non-nil and pushViewController is called correctly. [OK]
Quick Trick: pushViewController adds a new screen to the navigation stack [OK]
Common Mistakes:
  • Forgetting to unwrap navigationController optional
  • Confusing pushViewController with present method
  • Not setting the view controller's view properties before pushing

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes