Programmatically go back to previous ViewController in Swift

前端 未结 15 1526
野的像风
野的像风 2020-12-04 04:50

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 ba

相关标签:
15条回答
  • 2020-12-04 05:42

    Try this: for the previous view use this:

    navigationController?.popViewController(animated: true)  
    

    pop to root use this code:

    navigationController?.popToRootViewController(animated: true) 
    
    0 讨论(0)
  • 2020-12-04 05:43

    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")
            }
          }
        }
    }
    
    0 讨论(0)
  • 2020-12-04 05:44

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

    _ = navigationController?.popViewController(animated: true)
    
    0 讨论(0)
  • 2020-12-04 05:47

    Swift 3, Swift 4

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

    navigationController is optional because there might not be one.

    0 讨论(0)
  • 2020-12-04 05:47

    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 :)

    0 讨论(0)
  • 2020-12-04 05:51

    swift 5 and above

    case 1 : using with Navigation controller

    self.navigationController?.popViewController(animated: true)
    

    case 2 : using with present view controller

    self.dismiss(animated: true, completion: nil)
    
    0 讨论(0)
提交回复
热议问题