如何从弹出视图中关闭第二个视图控制器

How to dismiss second view controller from popup view

我有 2 个视图控制器 AB。视图控制器 A 通过 segue show 呈现视图控制器 BViewController B 也有一个关闭 B 并显示 A 的按钮。直到这里都没有问题。

B 中完成一些功能后,视图控制器 B 会显示一个弹出视图,该弹出视图包括重新启动游戏和关闭游戏按钮。当按下关闭游戏按钮时,View Controller B 和弹出视图应该被关闭并显示主 A 视图控制器。如何做到这一点?谢谢

如何呈现弹出视图:

let popupVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "popupID") as! PopupViewController
        self.addChildViewController(popupVC)
        popupVC.view.frame = self.view.frame
        self.view.addSubview(popupVC.view)
        popupVC.didMove(toParentViewController: self)

这里是 Swift3 中的解决方案。

据我了解,您想关闭 ViewController B 中显示的弹出窗口,然后 return 回到 ViewController A。

    let alertController = UIAlertController(title: "alert", message: "tara", preferredStyle: .alert)

    let action = UIAlertAction(title: "dismiss", style: .default) { (UIAlertAction) in

        // For Dismissing the Popup
        self.dismiss(animated: true, completion: nil)

        // Dismiss current Viewcontroller and back to ViewController B
        self.navigationController?.popViewController(animated: true)

    }
    alertController.addAction(action)
    self.present(alertController, animated: true, completion: nil)

实现这一点的传统方法是使用委托。在你的情况下,你必须首先为委托创建一个协议

protocol PopupViewControllerDelegate {
    func didSelectClose(_ popupVC: PopupViewController)
}

现在在 PopupViewController 中添加一个变量,它将用于调用委托的方法

class PopupViewController: UIViewController {
    var delegate: PopupViewControllerDelegate?
}

当用户点击弹出窗口中的 close 按钮时,您应该调用委托的方法来通知它用户的操作。

func didClose(sender: Any) {
    delegate?.didSelectClose(self)
}

现在,您必须在 ViewControllerB 中实现 PopupViewControllerDelegate,如下所示:

class ViewControllerB: UIViewController, PopupViewControllerDelegate {
    func didSelectClose(_ popupVC: PopupViewController) {
        // dismiss and go to Root View Controller (A)
        dismiss(animated: true) { 
            self.navigationController?.popToRootViewController(animated: true)
        }
    }
}

如您所见,调用 didSelectClose 时,我们关闭弹出窗口并弹出导航堆栈以转到 ViewControllerA

最后,在呈现 PopupVC 之前,您必须将 ViewControllerB 设置为委托

func showPopup() {
    let popupVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "popupID") as! PopupViewController

    popupVC.delegate = self
    present(popupVC, animated: true, completion: nil)
}