Pushing and popping view controllers.

UINavigationContoller manages views by pushing and popping them on/off the controller’ view stack. When you push an item, the current view slides off screen to the left, and the new view slides over from the right.

Today , I am going to explain how to push and pop ViewController off a UINavigatinalController Stack. And also how to allow to go to previous ViewController with the help of Swipe back gesture.

Step 1: Create Xcode Project

Now, create a new Xcode Project. This project will contain a single view controller, which is our main view controller.

Step 2: Embed UINavigationController

Now embed this view controller to UINavigationController by selecting Editor (form top menu) >> Embed In >> Navigation Controller. Double click on the title bar of the UITableViewController and name it as Example.

To Push ViewController.

let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)

let nextViewController = storyBoard.instantiateViewController(withIdentifier: "SecondViewControllerStoryBoardID") as! SecondViewController

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

To Pop ViewController.

1.  To pop to previous ViewController.

self.navigationController?.popViewController(animated: true);

2. To pop to root ViewController

self.navigationController?.popToRootViewController(animated: true)

3. To pop to Specific ViewController.

let controllers = self.navigationController?.viewControllers
      for vc in controllers! {
        if vc is SomeViewController {
          _ = self.navigationController?.popToViewController(vc as! SomeViewController, animated: true) } }

Pop ViewController by Swipe back gesture.

To pop ViewController by Swipe back gesture, you need to write below line in your viewDidLoad() function of ViewController which is to be popped  and make this ViewContoller a base Class of UIGestureRecognizerDelegate.

navigationController?.interactivePopGestureRecognizer?.delegate = self





Recent Post

Click to Copy