(Swift) 当多个视图控制器导致同一个视图时取消 segue?

(Swift) Unwind segue when multiple view controllers lead to same view?

我正在尝试编写 hangman 游戏的代码,但在展开 segues 时遇到了问题。我有多个视图控制器,它们最终都指向同一个视图,用户在其中扮演真正的刽子手。 但是,根据呈现控制器,我希望游戏处于不同的 "modes"(即:多人游戏、单人游戏等)。我正在尝试添加一个重新播放按钮,该按钮可以展开到之前的视图控制器,但是我不确定当用户可以通过多条路径到达此视图时如何展开。

换句话说,我的应用是:

A​​ -> B -> C 或

A​​ -> D -> C,其中 C 可以(理想情况下)展开到 D 或 B。

我想知道实现它的最佳方法是什么?我是否应该将所有视图控制器嵌入到导航控制器中?或者有没有办法根据特定条件呈现特定视图控制器?感谢您的帮助!

如果您将它推送到导航堆栈,我会简单地调用代码 popViewController:animated 转到呈现控制器,或者 dismissViewController:animated 如果它是模态呈现的。

unwind segue 过程通常会自动确定先前的 UIViewController 实例。 Apple Tech Note 中描述了确切的过程,但总结如下:

Starting from the view controller that initiated the unwind segue the search order is as follows:

  1. The next view controller in the responder chain is sent a viewControllerForUnwindSegueAction:fromViewController:withSender: message. For a view controller presented modally, this will be the view controller that called presentViewController:animated:completion:. Otherwise, the parentViewController.

    The default implementation searches the receiver's childViewControllers array for a view controller that wants to handle the unwind action. If none of the receiver's child view controllers want to handle the unwind action, the receiver checks whether it wants to handle the unwind action and returns self if it does. In both cases, the canPerformUnwindSegueAction:fromViewController:withSender: method is used to determine if a given view controller wants to handle the unwind action.

  2. If no view controller is returned from viewControllerForUnwindSegueAction:fromViewController:withSender: in step one, the search repeats from the next view controller in the responder chain.

因此,精确的过程将取决于您如何呈现视图控制器 C - 例如,通过模态呈现转场或 UINavigationController 上的推送转场,但只要 B 和 D 都实现展开行动你应该是好的。

如果您有任何自定义逻辑并希望以编程方式调用展开转场到不同的视图控制器,方法如下:

  1. unwindFromCViewController添加到BViewControllerDBViewController

    BViewController.swift

    class BViewController : UIViewController {
        @IBAction func unwindFromCViewController(segue:UIStoryboardSegue) {
        }
    }
    

    DViewController.swift

    class DViewController : UIViewController {
        @IBAction func unwindFromCViewController(segue:UIStoryboardSegue) {
        }
    }
    
  2. 在你的故事板中,创建这个 segue 并给它一个标识符,然后 link 它到你上面定义的动作 unwindFromCViewController:

  1. 从代码调用展开转场:

    self.performSegueWithIdentifier("unwindFromCViewControllerSugueId", sender: self)
    

这样一来,无论它来自何处,您都可以放松到之前的视图。