如何在Swift 3中使用unwind(for: UIStoryboardSegue, towardsViewController: UIViewController)?

How to use unwind(for: UIStoryboardSegue, towardsViewController: UIViewController) in Swift 3?

我使用 Apple 示例代码。 最初该方法看起来像这样

@IBAction func doneTapped() {
    favoriteCreatureDidChange?(favoriteCreature)
    dismiss(animated: true, completion: nil)
}

我将 Segue Kind 从 Present Modally 更改为 Show(例如 Push)。因此,dismiss 不再起作用,我需要使用 Unwind Segue 来回到我之前的 VC.

不是在SourceVC中声明IBAction的情况,因为我需要执行favoriteCreatureDidChange?(favoriteCreature) - 变量,在我当前所在的VC中声明。

我想我需要使用unwind(for: UIStoryboardSegue, towardsViewController: UIViewController)

据我所知,对于 for: 参数,我需要使用一个在当前 VC.

中转移我的 segue

我正在尝试获取 segue 的实例

let segue = UIStoryboardSegue(identifier: "showFavoriteCreaturePicker", source: DreamListViewController, destination: FavoriteCreatureListViewController)

但是 Xcode 抱怨 Cannot convert value of type 'DreamListViewController.Type' to expected argument type 'UIViewController' 虽然 FavoriteCreatureListViewController 一切正常。

请告诉我如何将 segue 传递给 for: 参数而不出错。

此初始化程序需要控制器实例,而不是控制器类型。但是,请注意 UIStoryboardSegue documentation:

You do not create segue objects directly. Instead, the storyboard runtime creates them when it must perform a segue between two view controllers. You can still initiate a segue programmatically using the perform​Segue(with​Identifier:​sender:​) method of UIView​Controller if you want. You might do so to initiate a segue from a source that was added programmatically and therefore not available in Interface Builder.

此外,您仅在自定义转场中使用此初始化程序:

If you need to initialize any variables in your custom segue subclass, you can also override the init(identifier:​source:​destination:​) method and initialize them in your custom implementation.

至于 unwind(for:​towards​View​Controller:​)the documentation 是这样说的(强调我的):

During the execution of an unwind segue, UIKit calls this method on any view controllers in the unwind path to give them an opportunity to reconfigure themselves. Container view controllers must implement this method and use to display the view controller in the subsequent​VC parameter. For example, a tab bar controller selects the tab containing the specified view controller. Noncontainer view controllers should not override this method.

最后,解决方案:您可以在 Interface Builder 中创建展开转场,并在启动展开的视图控制器中重写 prepare(for:sender:):

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    super.prepare(for: segue, sender: sender)
    favoriteCreatureDidChange?(favoriteCreature)
}

这将在调用展开转场的目标视图控制器中的展开操作之前调用。

另请注意UINavigationController中有pop​View​Controller(animated:​)