简体   繁体   中英

push ViewController without storyboard

I try to push a view controller from the main ViewController like this (Swift 4):

@objc func childAction(sender: UIButton!) {
    print("Child button tapped")
    let vc = childDetailViewController()
    self.navigationController?.pushViewController(vc, animated: true)
}

The text is printed, but the viewController is not pushed. What did I missed?

Possible that self.navigationController is nil .

Try to present it: self.present(vc, animated: true)

UPD

Also if it does not help, try temporary change your childDetailViewController to UIViewController() and see what happens. If you see the empty white screen after tap then the problem is on childDetailViewController

Inside AppDelegate 's didFinishLaunchingWithOptions do

let fir = FirstVC()
self.window?.rootViewController = UINavigationController(rootViewController: fir)

Then this

self.navigationController?.pushViewController(vc, animated: true)

should work

From Xcode 11 you might have noticed that along with the default files like above, a new file is created named as SceneDelegate.swift. From iOS 13 and later, SceneDelegate takes up some responsibilites from AppDelegate. In particular related to UIWindow from AppDelegate is now UIScene in SceneDelegate. An app can have more than one scene which mostly handles application interface and app content. So, the SceneDelegate is responsible for what's displayed on the screen in terma of UI and data.

var window: UIWindow?


func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
   
    guard let windowScene = (scene as? UIWindowScene) else { return }
    window = UIWindow(windowScene: windowScene)
    let vc = ViewController()
    let navigationView = UINavigationController(rootViewController: vc)
    window?.rootViewController = navigationView
    window?.makeKeyAndVisible()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM