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

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

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

正确的做法是什么?


当前回答

Swift 5及以上

案例1:与导航控制器一起使用

回到之前的视图控制器 self.navigationController ?。会被(动画:真) 回到根视图控制器 self.navigationController ?。popToRootViewController(动画:真)

案例2:使用present视图控制器

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

其他回答

在这种情况下,你从UIViewController中呈现一个UIViewController,也就是。

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

简单地调用dismiss函数:

// Other View Controller
self.dismiss(animated: true)

对于swift 3 您只需要编写下面这行代码

_ = navigationController?.popViewController(animated: true)

我是这样做的

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

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

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

如果你想关闭前两个视图控制器,只需像这样调用popViewController两次:

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