Popping ViewController on Swift
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)
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.
erdemgc
Updated on July 09, 2022Comments
-
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 over 8 yearsThis basically has the same effect as optional chaining; it works if it's not nil and does nothing if it is.
-
seanscal about 7 years
_ =
is not needed here -
Anit Kumar about 7 yearsIf you are not using return type of variable then you can written like this _ =
-
SafeFastExpressive about 6 yearsThis is no different than the question's code in effect.
-
Dale Clifford about 6 yearsYes! I needed to get the navigationController of the navigationController!!
-
Codetard over 2 yearsWow! Works in the case of split view controller. +1