0

I created simple project with two ViewControllers (ViewController and SecondVC) programmatically. In ViewController I've added a button, which push to SecondVC. In AppDelegate didFinishLaunchingWithOptions I've set ViewController as rootViewController.

ViewController code:

class ViewController: UIViewController {
   let button = UIButton.init(frame: CGRect(x: 30, y: 30, width: 200, height: 200))

   override func viewDidLoad() {
       super.viewDidLoad()
       view.backgroundColor = .brown
       view.addSubview(button)
       button.backgroundColor = .black
       button.addTarget(self, action: #selector(tapped), for: .touchUpInside)
   }

   @objc func tapped() {
       let vc = SecondVC()
       self.navigationController?.pushViewController(vc, animated: true)
   }
}

SecondVC code:

class SecondVC: UIViewController {

    override func viewDidLoad() {
       view.backgroundColor = .white
    }
}

AppDelegate code:

class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?
var navigationController: UINavigationController?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    window = UIWindow(frame: UIScreen.main.bounds)

    if let window = window {
        let mainVC = ViewController()
        navigationController = UINavigationController(rootViewController: mainVC)
        window.rootViewController = navigationController
        window.makeKeyAndVisible()
    }

    return true
}

In targets deployment info I've removed Main Interface:

Image of Main Interface

When app starts, there is no navigation in my ViewController, so when I tap on button, navigationController is nil, and nothing happens. Cannot find the problem the second day, please help to understand where the problem is. I use XCode 11.3

sources like these, doesn't help me Creating a navigationController programmatically (Swift)

Bah G
  • 29
  • 7

1 Answers1

1

Your code works just fine. I copied it and pasted it into a new project and this is what I saw at launch:

enter image description here

I tapped the big black square and we slide to the side and this is what I saw:

enter image description here

My guess as to why it doesn't work for you is that you are using Xcode 11. If so, the issue is that the app delegate is not where the work of launching the app's interface takes place: it's the scene delegate. But you can change that by following the instructions here: https://stackoverflow.com/a/57467270/341994

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Thank you, it was my problem. I use XCode 11.3 Removing the “Application Scene Manifest” entry from Info.plist and scene related methods in my app delegate, helped me – Bah G Feb 19 '20 at 07:04