iNishinKareem iNishinKareem - 1 month ago 11
iOS Question

Calling parent View Controller function from a subview

I have a parent ViewController with two subview controllers.

When I load the parent view controller it will display two of the subviews. I can also swipe left or right to slide subviews. I now have a requirement to add a button on subviews. On clicking the button it should slide automatically to next subview.

This is what i'm planning - place a button on subview viewcontroller. Hitting the button will call a function in parent viewcontroller that is responsible for sliding. right now i'm unable to call parent viewcontroller's function. I need the current instance of parent view controller.
Can someone please help?

on the picture, grey is subview viewcontroller 1
green is is subview viewcontroller 2.
clicking on button of viewcontroller1 should slide to viewcontroller 2

Please click here for screen print


There are two solutions I can think of off the top of my head:

  1. Make your button a subview of the parent view controller; this will obviously not work if you want your button to be a subview of one of the child view controller views;
  2. To expand on @NazmulHasan's suggestion, you could implement a custom protocol for your child view controllers. To take child view controller 1 as an example, you simply need to declare a delegate protocol for that class. This tells the compiler which functions the delegate of the view controller has to implement to satisfy the protocol. So you'd do something like this:

    protocol childViewControllerOneDelegate { func buttonWasPressed(sender: UIButton) -> Void {

You also need to add a property to your child view controller as follows:

var myDelegate : childViewControllerOneDelegate!

It's an implicitly unwrapped optional because you cannot set the delegate when the class is initialized; you set it as I'm going to outline below.

At the very top of your parent view controller class declaration, you then declare that the view controller complies with this protocol:

class parentViewController : UIViewController, childViewControllerOneDelegate ... Etc, etc {

When you initialize childViewControllerOne from the parent view controller, you can then add a line straight afterwards that says:

myChildViewControllerOne.delegate = self

Finally, going back to your button and the child view controller, you simply add an action to it that calls the following:


This will trigger the method in the parent view controller and you can do whatever you need to do.

Hope that helps. As always with these answers, I'm trying to compress a lot of info into a small space, so drop me a line if you have any questions. All best!