使用 UITableView iOS swift 以编程方式按下 UIViewController 的后退按钮

Programmatically press back button for UIViewController with UITableView iOS swift

我有一个 UIViewController,它实现了 UITableViewDelegate、UITableViewDataSource 并且包含一个 UITableView 作为成员变量。当用户单击 table 的其中一行时,应用程序会执行故事板转场以打开详细视图控制器。该详细视图控制器当然在屏幕的左上角有一个按钮,该按钮是 "back" 按钮,用于使用 UIViewTable 返回到 UIViewController。

所以,假设我想以编程方式 "click" 那个后退按钮。在 swift 中我该怎么做?这是 swift(swift 4?)在 XCode 10.1 中的最新版本。

更新:

这就是我解决这个问题的方法。正如下面的答案所示,可以使用 self.navigationController?.popViewController(animated: true) 只是 return 到前一个视图控制器。然而,我发现我还想做的是调用该视图控制器中的特定方法,以便它在显示后执行特定行为。事实证明这也是可能的,但在我的例子中它有点棘手,因为之前的视图控制器实际上是一个 UITabBarController。因此,我必须从 UITabBarController 中获取我感兴趣的 ViewController。我是这样做的:

let numvc = navigationController!.viewControllers.count
let tvc:UITabBarController = navigationController!.viewControllers[numvc-2] as! UITabBarController
let my_vc: MyCustomVC = tvc.viewControllers![0] as! MyCustomVC
my_vc.some_function()

当然,这里的 MyCustomV 是我的自定义视图控制器 class,而 some_function() 是我想在 class 上调用的方法。希望这对某人有所帮助。

当你 运行 一个 segue 你执行一个 "pushViewController" 方法到下一个视图,所以如果你想以编程方式返回到前一个视图,你只需要弹出最后一个视图像这样:

self.navigationController?.popViewController(animated: true)

更新 你只需要 if 语句 如果你有多个 segues 来自 viewController,如果没有,你可以删除并只投下一个根据需要查看并设置属性,让自动完成为您编写 *prepare(for segue... * 方法,这样您就不会 运行 遇到任何问题

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "yourSegueName" {
        let destinationVC = segue.destination as! CustomViewController
        destinationVC.labelExample.text = "Some text I'm sending"
    }
}

您确定需要"click"按钮吗?

  • 如果您只需要关闭详细信息视图控制器,您只需调用 navigationController?.popViewController(animated: true)
  • 或者如果你想直接处理按钮,你可以告诉它发送它的动作:backButton.sendActions(for: .touchUpInside)
  • 或者如果你绝对需要显示按钮点击动画,那么你将需要这样的东西(你应该播放并选择合适的延迟):
    backButton.isHighlighted = true
    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
        backButton.isHighlighted = false
        backButton.sendActions(for: .touchUpInside)
    }