erdemgc
erdemgc

Reputation: 1721

Popping ViewController on Swift

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?

Upvotes: 50

Views: 84998

Answers (4)

Anit Kumar
Anit Kumar

Reputation: 8153

Swift 3.0 This is working for me

self.navigationController?.popViewController(animated: true)

enter image description here

Upvotes: 25

karlofk
karlofk

Reputation: 1215

You need to unwrap your navigationController correctly

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

Upvotes: 99

spaceMonkey
spaceMonkey

Reputation: 4615

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.

Upvotes: 9

Aleksi Sjöberg
Aleksi Sjöberg

Reputation: 1474

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.

Upvotes: 6

Related Questions