swiftnavigationcontrollertabbed

Swift: How to access second view after navigation controller?


I'm really new to swift and currently working on a project for a trivia app. Right now I have it so that after pressing the start button, it pushes aside the current view controller and shows the user a new one (vc), but I'm not sure how/where to add textfields and buttons to that new view (vc) that the user sees after pressing start.


       
       let vc = UIViewController()
       vc.view.backgroundColor = .red
       
       navigationController?.pushViewController(vc, animated: true) 

Solution

  • You have to create another view controller with UI in it.

       class SecondViewController: UIViewController {
           private let textView = UITextView()
           
           func viewDidLoad() {
               super.viewDidLoad()
               
               // Add text view with auto layout
               view.addSubview(textView)
               textView.translatesAutoresizingMaskIntoConstraints = false
               textView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
               textView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
               textView.heightAnchor.constraint(equalToConstant: 44).isActive = true
           }
       }
    

    Then when trying to push a new view controller use this SecondViewController

       let vc = SecondViewController()
       vc.view.backgroundColor = .red
       
       navigationController?.pushViewController(vc, animated: true)