261

I send the user over to a page on a button click. This page is a UITableViewController.

Now if the user taps on a cell, I would like to push him back to the previous page.

I thought about something like self.performSegue("back").... but this seems to be a bad idea.

What is the correct way to do it?

1
  • 15
    self.navigationController?.popViewControllerAnimated(true)
    – Kalpesh
    Feb 27, 2015 at 8:31

16 Answers 16

628

Swift 3:

If you want to go back to the previous view controller

_ = navigationController?.popViewController(animated: true)

If you want to go back to the root view controller

_ = navigationController?.popToRootViewController(animated: true)

If you are not using a navigation controller then pls use the below code.

self.dismiss(animated: true, completion: nil)

animation value you can set according to your requirement.

10
  • 1
    How can I send data back to previousController when the cell is tapped? if we are using the navigationController?.popViewControllerAnimated(true)
    – JDDelgado
    Sep 17, 2015 at 2:07
  • 4
    @JDDelgado This is how you send the data back with the user, stackoverflow.com/questions/12561735/… Oct 18, 2015 at 18:13
  • 36
    For Swift 3 it is .popViewController(animated: true)
    – Sasho
    Oct 5, 2016 at 8:37
  • 10
    To shush any warnings: _ = self.navigationController?.popToRootViewController(animated: true)
    – Andrew K
    Oct 29, 2016 at 17:45
  • 1
    We are ignoring the return value; _ = is the convention in swift for that.
    – Andrew K
    Oct 30, 2016 at 16:10
62

Swift 3, Swift 4

if movetoroot { 
    navigationController?.popToRootViewController(animated: true)
} else {
    navigationController?.popViewController(animated: true)
}

navigationController is optional because there might not be one.

6
  • @Vyacheslva i am getting an error "implicit use of 'seft' in closure, use 'self' to make capture semantics explicit" Apr 20, 2017 at 3:05
  • @SandipSubedi use [weak self] and self?.navigationController?.
    – Vyacheslav
    Apr 20, 2017 at 10:00
  • this was useful But I want to send some variables with navigation But now I can't - I used override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let vc = segue.destination as? But when I using this I can't use that Jan 2, 2018 at 12:58
  • how to add navigationController then?
    – user25
    Feb 28, 2018 at 13:07
  • @user25 add? what do you mean?
    – Vyacheslav
    Feb 28, 2018 at 16:45
41

swift 5 and above

case 1 : using with Navigation controller

  • Back to the previous view controller

     self.navigationController?.popViewController(animated: true)
    
  • Back to the root view controller

    self.navigationController?.popToRootViewController(animated: true)
    

case 2 : using with present view controller

self.dismiss(animated: true, completion: nil)
40

Swift 3

I might be late in the answer but for swift 3 you can do it this way:

override func viewDidLoad() {
    super.viewDidLoad()

    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "< Back", style: .plain, target: self, action: #selector(backAction))

    // Do any additional setup if required.
}

func backAction(){
    //print("Back Button Clicked")
    dismiss(animated: true, completion: nil)
}
6
  • 3
    That's not 'fully' correct. If you present a view controller that contains its own navigation, and after you push a view controller use that method dismiss: it will not only dismiss the current view controller, but also the root view controller, and it's not what was asked here. Feb 2, 2017 at 12:16
  • 2
    The question did not ask if the user had a navigation controller. This is the simplest and best answer for no navigation controller. This should really be the accepted answer. Feb 5, 2017 at 5:25
  • Thanks Droid - Hi ernestofndz, you might be right in saying that the rootVC will also be dismissed, but this does not happen with me, it only dismisses the currentVC, i am adding and removing items programmatically, and it might not be the same approach with the normal adding elements on storyboard.. correct my understanding if i am wrong... for the tableView if user needs to pass details to another View then this is another case and has no linkage to what i have posted and will 100% agree with you..what i understood was that a Back button is required in this case :)
    – Fullpower
    Feb 8, 2017 at 13:10
  • maybe u can add a little introduction.. because exist dismiss & navigationController?.popViewController
    – marlonpya
    Sep 11, 2017 at 15:24
  • dismiss(animated: true, completion: nil) doesn't work after rotation!
    – user924
    Aug 7, 2018 at 6:56
38

Swift 4

there's two ways to return/back to the previous ViewController :

  1. First case : if you used : self.navigationController?.pushViewController(yourViewController, animated: true) in this case you need to use self.navigationController?.popViewController(animated: true)
  2. Second case : if you used : self.present(yourViewController, animated: true, completion: nil) in this case you need to use self.dismiss(animated: true, completion: nil)

In the first case , be sure that you embedded your ViewController to a navigationController in your storyboard

0
24

In the case where you presented a UIViewController from within a UIViewController i.e...

// Main View Controller
self.present(otherViewController, animated: true)

Simply call the dismiss function:

// Other View Controller
self.dismiss(animated: true)
1
  • self.dismiss(animated: true) - doesn't work after rotation
    – user924
    Aug 7, 2018 at 6:56
11

If Segue is Kind of 'Show' or 'Push' then You can invoke "popViewController(animated: Bool)" on Instance of UINavigationController. Or if segue is kind of "present" then call "dismiss(animated: Bool, completion: (() -> Void)?)" with instance of UIViewController

7

for swift 3 you just need to write the following line of code

_ = navigationController?.popViewController(animated: true)
0
4

This one works for me (Swift UI)

struct DetailView: View {
@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>

  var body: some View {
      VStack {
        Text("This is the detail view")
        Button(action: {
          self.presentationMode.wrappedValue.dismiss()
        }) {
          Text("Back")
        }
      }
    }
}
3

Try this: for the previous view use this:

navigationController?.popViewController(animated: true)  

pop to root use this code:

navigationController?.popToRootViewController(animated: true) 
0
2

Swift 4.0 Xcode 10.0 with a TabViewController as last view

If your last ViewController is embebed in a TabViewController the below code will send you to the root...

navigationController?.popToRootViewController(animated: true)
navigationController?.popViewController(animated: true)

But If you really want to go back to the last view (That could be Tab1, Tab2 or Tab3 view..)you have to write the below code:

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

This works for me, i was using a view after one of my TabView :)

2

I would like to suggest another approach to this problem. Instead of using the navigation controller to pop a view controller, use unwind segues. This solution has a few, but really important, advantages:

  1. The origin controller can go back to any other destination controller (not just the previous one) without knowing anything about the destination.
  2. Push and pop segues are defined in storyboard, so no navigation code in your view controllers.

You can find more details in Unwind Segues Step-by-Step. The how to is better explained in the former link, including how to send data back, but here I will make a brief explanation.

1) Go to the destination (not the origin) view controller and add an unwind segue:

    @IBAction func unwindToContact(_ unwindSegue: UIStoryboardSegue) {
        //let sourceViewController = unwindSegue.source
        // Use data from the view controller which initiated the unwind segue
    }

2) CTRL drag from the view controller itself to the exit icon in the origin view controller:

Unwind from view controller

3) Select the unwind function you just created a few moments ago:

Select unwind function

4) Select the unwind segue and give it a name:

Naming unwind segue

5) Go to any place of the origin view controller and call the unwind segue:

performSegue(withIdentifier: "unwindToContact", sender: self)

I have found this approach payoffs a lot when your navigation starts to get complicated.

I hope this helps someone.

1

For questions regarding how to embed your viewController to a navigationController in the storyboard:

  1. Open your storyboard where your different viewController are located
  2. Tap the viewController you would like your navigation controller to start from
  3. On the top of Xcode, tap "Editor"
  4. -> Tap embed in
  5. -> Tap "Navigation Controller
0

I did it like this

func showAlert() {
    let alert = UIAlertController(title: "Thanks!", message: "We'll get back to you as soon as posible.", preferredStyle: .alert)

    alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
        self.dismissView()
    }))

    self.present(alert, animated: true)
}

func dismissView() {
    navigationController?.popViewController(animated: true)
    dismiss(animated: true, completion: nil)
}
0

If you want to close previous two view controllers just call popViewController two times like this way:

self.navigationController?.popViewController(animated: true)
self.navigationController?.popViewController(animated: true)
-4

I can redirect to root page by writing code in "viewDidDisappear" of navigated controller,

override func viewDidDisappear(_ animated: Bool) { self.navigationController?.popToRootViewController(animated: true) }

1
  • This causes the navigation controller to pop to the root, even if you want to move forward in the hierarchy.
    – swiftyboi
    Apr 21, 2017 at 20:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.