从呈现的视图控制器访问呈现的视图控制器? [英] Access the presenting view controller from the presented view controller?

查看:79
本文介绍了从呈现的视图控制器访问呈现的视图控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在另一个视图控制器(我的应用程序)的顶部显示了一个视图控制器(包含我的菜单).

I have a view controller (containing my menu) presented on top of another view controller (my application).

我需要从呈现的视图控制器(我的菜单)访问呈现的视图控制器(在我的菜单下方),例如访问一些变量或使呈现的视图控制器执行其选择之一.

I would need to access the presenting view controller (below my menu) from the presented view controller (my menu), for example to access some variables or make the presenting view controller perform one of its segues.

但是,我只是不知道该怎么做. 我知道"presentingViewController"和"presentedViewController"变量,但是我没有成功使用它们.

However, I just can't figure out how to do it. I'm aware of the "presentingViewController" and "presentedViewController" variables but I didn't manage to use them successfully.

有什么主意吗?

代码(来自提供的VC,作为对引用窗口的AppDelegate的引用):

Code (from the presented VC, which as a reference to the AppDelegate in which the window is referenced) :

if let presentingViewController = self.appDelegate.window?.rootViewController?.presentingViewController {
    presentingViewController.performSegue(withIdentifier: "nameOfMySegue", sender: self)
}

推荐答案

这里是使用委托设计模式来与呈现视图控制器进行对话.

Here is a use of the delegation Design pattern to talk back to the presenting view controller.

首先声明一个协议,该协议列出了委托期望响应的所有变量和方法.

First Declare a protocol, that list out all the variables and methods a delegate is expected to respond to.

protocol SomeProtocol {

    var someVariable : String {get set}

    func doSomething()
}

下一步:使您的呈现视图控制器符合协议. 将您要呈现的VC设置为委托人

Next : Make your presenting view controller conform to the protocol. Set your presenting VC as the delegate

class MainVC: UIViewController, SomeProtocol {

    var someVariable: String = ""

    func doSomething() {
        // Implementation of do
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Your code goes here.

        if let destVC = segue.destination as? SubVC{
            destVC.delegate = self
        }
    }

}

最后,当您准备在显示的VC(代理)上调用方法时.

Finally, when you are ready to call a method on the presenting VC (Delegate).

class SubVC: UIViewController {
    var delegate : SomeProtocol?


    func whenSomeEventHappens() {

        // For eg : When a menu item is selected

        // Set some Variable
        delegate?.someVariable = "Some Value"

        // Call a method on the deleate
        delegate?.doSomething()
    }

}

这篇关于从呈现的视图控制器访问呈现的视图控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆