iosswiftpushviewcontroller

how to use navigation controller programaticaly?


i have a button in viewcontroller which navigates to editPage viewcontrooler

i want to use pushNavigation

i did below code in button action method

 @IBAction func editBtn(_ sender: Any) {
        let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let newViewController = storyBoard.instantiateViewController(withIdentifier: "editProfile") as! editProfile
        let navigation = UINavigationController(rootViewController: newViewController)
        self.navigationController?.pushViewController(navigation, animated: true)
 }

but when i click on button it dosent navigate

i dont have navigation controler in storyboard.......

i dont want to present view controler


Solution

  • Looks like you are setting your viewController as initail View Controller from storyboard but do not embed this in navigation controller , either embed your viewController in navigationController and set this navigation controller as initialViewController or follow this approach as you don't want to do it from storyboard:

    In SceneDelegate , write :

    var window: UIWindow?
    

    and then in this method :

     func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
            // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
            // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
            // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
            guard let _ = (scene as? UIWindowScene) else { return }
            //Setup user state
          
            if let vc = UIStoryboard.init(name: "YOUR_STORYBOARD_NAME", bundle: nil).instantiateViewController(withIdentifier: "VIEW_CONTROLLER_IDENTIFIER") as? ViewController {
                let nav = UINavigationController(rootViewController: vc)
                window?.rootViewController = nav
                window?.makeKeyAndVisible()
            }
        }
    

    for IOS < 13, in AppDelegate.swift :

    var window : UIWindow?
        
        //MARK:- DID FINISH LAUNCHING WITH OPTIONS : CALLED EVERYTIME WHEN APPLICATION LAUNCHES
        
        func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
            if let vc = UIStoryboard.init(name: "YOUR_STORYBOARD_NAME", bundle: nil).instantiateViewController(withIdentifier: "VIEW_CONTROLLER_IDENTIFIER") as? ViewController {
                      let nav = UINavigationController(rootViewController: vc)
                      window?.rootViewController = nav
                      window?.makeKeyAndVisible()
                  }
           
            return true
        }