One option is to use NotificationCenter
, have your buttons post the notification, and have your child view controller listen for them.
For example, in the parent VC, post the notification in the function called when a button is tapped, like so:
@IBAction func buttonTapped(_ sender: UIButton) {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "ButtonTapped"), object: nil, userInfo: nil)
}
In the child VC that needs to respond to the button tap, place the following code in viewWillAppear:
to set the VC as a listener for that specific notification:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(handleButtonTap(_:)), name: NSNotification.Name(rawValue: "ButtonTapped"), object: nil)
}
In the same view controller, add the handleButtonTap:
method mentioned above. When the "ButtonTapped" notification comes in, it will execute this method.
@objc func handleButtonTap(_ notification: NSNotification) {
//do something when the notification comes in
}
Don't forget to remove the view controller as an observer when it is no longer needed, like this:
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self)
}