Search code examples
iosswiftxcodeviewcontroller

Get the presenting viewController of viewController.view in swift


i am trying to get the presenting viewController of a viewController's view The idea is like that : i have a

viewController = CategoriesViewController

and i am presenting its view inside anther

viewController = HomeViewController

by using

CategoriesViewController.view so when i want to reach the

HomeViewController from CategoriesViewController

i do this

let vc = self.presentingViewController as? HomeViewController

but it is telling me that it is nil i tried the

.parentViewController

and it is returning

CategoriesViewController


Solution

  • In case you want to change a variable in HomeVieController using CategoriesViewController you could create your own protocol. You can use protocols to communicate between different controllers.

        protocol ChangeVariableProtocol {
                func changeVar(variable: Int)
            }
    
    

    In the protocol itself you only declare methods. In your CategoriesViewController you would create a delegate Varibale like this

    var changeVarDelegate: ChangeVariableProtocl?

    Whenever you want to change the variable in CategoriesViewController you call your protocol method.

    changeVarDelegate?.changeVar(10)

    In HomeViewController you need to implement this protocol and initialize the changeVarDelegate variable.

        extension HomeViewController: ChangeVarProtocol {
            func changeVar(var: variable) {
               // Implement your own logic here
             self.valueToChange = variable
            }
    
    

    And make sure that you initialize changeVarDelegate when you are instancing your CategoriesViewController.

    Hope this helps!