我将用户发送到一个页面上的按钮点击。这个页面是一个UITableViewController。

现在如果用户点击一个单元格,我想把他推回到上一页。

我想到了self.performSegue("back")....但这似乎不是一个好主意。

正确的做法是什么?


当前回答

Swift 4.0 Xcode 10.0与TabViewController作为最后一个视图

如果你的上一个ViewController是嵌入在一个TabViewController中,下面的代码将把你发送到根…

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

但如果你真的想回到上一个视图(可能是Tab1, Tab2或Tab3视图..),你必须写下面的代码:

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

这对我来说是有效的,我在我的TabView之后使用了一个视图:)

其他回答

我是这样做的

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

这个很适合我(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

我可能回答得晚了,但对于swift 3,你可以这样做:

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

如果Segue是“Show”或“Push”类型,那么你可以在UINavigationController的实例上调用“popViewController(animated: Bool)”。或者如果segue是present,那么调用UIViewController的实例"dismiss(animated: Bool, completion: (() -> Void)?

我可以通过在导航控制器的“viewDidDisappear”中写代码重定向到根页面,

override func viewDidDisappear(_ animated: Bool) { self.navigationController ?。popToRootViewController(动画:真) }