There are two solutions I can think of off the top of my head:
- 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.
- 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:
self.myDelegate.buttonWasPressed(self.button)
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!