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

时间:2017-06-22 13:31:39

标签: ios swift uiviewcontroller popup viewcontroller

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

B中完成某些功能后,视图控制器B会显示一个弹出视图,此弹出窗口包括重启游戏和关闭游戏按钮。当按下关闭游戏按钮时,应取消查看控制器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)

2 个答案:

答案 0 :(得分:2)

这是Swift3中的解决方案。

据我了解,您想要关闭ViewController B中提供的弹出窗口并返回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)

答案 1 :(得分:2)

实现此目的的传统方法是使用委托。在您的情况下,您必须首先为委托创建协议

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