So I've got a viewcontroller in which there's a child container layout, I need to call a method in that child only when I press a button in the parent. How to do that?
Asked
Active
Viewed 176 times
2 Answers
0
our initial view controller should have a reference to the child container. make sure you save that reference in a var or let which is accessible to the whole class (define it in the very beginning of the view controller, outside of any functions). then you can just call the method you need from the button press function by something like childContainer.method()

Tahdiul Haq
- 245
- 3
- 11
0
When you use a UIContainerView
, Storyboard automatically sets up an embed segue. You can use prepareForSegue
to get a reference to the child VC.
Here's a very simple example:
class MyChildViewController: UIViewController {
func funcInChild(_ val: String) -> Void {
print("funcInChild was called with: \(val)")
}
}
class MainViewController: UIViewController {
var childInContainer: MyChildViewController?
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let vc = segue.destination as? MyChildViewController {
childInContainer = vc
}
}
@IBAction func btnTapped(_ sender: Any?) -> Void {
childInContainer?.funcInChild("This is a test!")
}
}

DonMag
- 69,424
- 5
- 50
- 86