Swift how to navigate from one view controller to another

Step 1: Make sure you define UINavigationController in the AppDelegate


import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        let mainStoryboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let mainViewController = mainStoryboard.instantiateInitialViewController()
        let navigationController = UINavigationController(rootViewController: mainViewController!)
        
        self.window = UIWindow(frame: UIScreen.main.bounds)
        self.window?.rootViewController = navigationController
        self.window?.makeKeyAndVisible()
        
        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
    }

    func applicationWillTerminate(_ application: UIApplication) {
    }


}

Step 2: Based on some action such as Button Click push the next view controller using the navigation controller


@objc func buttonAction(sender: UIButton!) {
        if let buttonTitle = sender.titleLabel?.text {
            print(buttonTitle + " tapped!")
            if buttonTitle == "My first Button" {
                print(buttonTitle + " tapped!")
                
                //Now push the next view controller 
                let nyNextVC = MyNextViewController(nibName: "MyNextViewController", bundle: nil)
                self.navigationController?.pushViewController(nyNextVC, animated: true)
            }
        }
    }

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.