Popping ViewController on Swift

74,107

Solution 1

You need to unwrap your navigationController correctly

if let navController = self.navigationController {
    navController.popViewController(animated: true)
}

Solution 2

Swift 3.0 This is working for me

self.navigationController?.popViewController(animated: true)

enter image description here

Solution 3

In my case im using a Master Details view ( Split View Controller ). My details view controller is embedded inside an navigation controller. So when i wanted to dismiss my Details view controller. I had to pop it from the navigation controller of the parent (Split view controller) Like this.

_ = self.navigationController?.navigationController?.popViewController(animated: true)

hope this helps someone.

Solution 4

It seems that the view controller you're working with isn't embedded in Navigation Controller. If there was a Navigation Controller, i.e. self.navigationController is not nil, both lines should work just as well even though the latter one is preferred as it uses optional chaining.

Make sure you have embedded your View Controller in a Navigation Controller. You can do it by selecting the View Controller in Storyboard editor and clicking Editor -> Embed In -> Navigation Controller. Also make sure that you have your Storyboard Entry Point (the arrow that indicates which view controller is presented first) either pointing to Navigation Controller or before it.

Share:
74,107
erdemgc
Author by

erdemgc

Updated on July 09, 2022

Comments

  • erdemgc
    erdemgc almost 2 years

    I need to pop a UIViewController from the navigation controller.

    Just writing this line of code but taking an exception;

    unexpectedly found nil while unwrapping an Optional value

    self.navigationController.popViewControllerAnimated(true)
    

    If I make the navigation controller optional, this line makes no effect, no popping

    self.navigationController?.popViewControllerAnimated(true)
    

    How to solve it?

  • Aleksi Sjöberg
    Aleksi Sjöberg over 8 years
    This basically has the same effect as optional chaining; it works if it's not nil and does nothing if it is.
  • seanscal
    seanscal about 7 years
    _ = is not needed here
  • Anit Kumar
    Anit Kumar about 7 years
    If you are not using return type of variable then you can written like this _ =
  • SafeFastExpressive
    SafeFastExpressive about 6 years
    This is no different than the question's code in effect.
  • Dale Clifford
    Dale Clifford about 6 years
    Yes! I needed to get the navigationController of the navigationController!!
  • Codetard
    Codetard over 2 years
    Wow! Works in the case of split view controller. +1