Call function of child view instance from parent view controller

2k Views Asked by At

I have a motherView controlled by motherViewController with a container view in it. The container view is controlled by an childViewController. The childView holds an tableView.

Now I have a cleanTableView function in the childViewController, which "resets" the tableView when called.

func clean() {
    let indexPath = IndexPath(row: 0, section: 0)
    if let cell = tableView.cellForRow(at: indexPath) {
        if cell.accessoryType == .checkmark {
            cell.accessoryType = .none
        }
    }
}

In my motherView there is a button. When this button is touched it calls an action on motherViewController.

@IBAction func cancelButtonTapped(_ sender: UIBarButtonItem) {

       //call clean method of containerView instance

}

How do I call, from this action, the cleanTableView function on the specific childView Instance?

2

There are 2 best solutions below

5
André Slotta On BEST ANSWER

Assuming there is only one child view controller:

@IBAction func cancelButtonTapped(_ sender: UIBarButtonItem) {
    (children.first as? ChildViewController)?.clean()
}

Some additional information regarding an API change / renaming:

The childViewControllers property has been renamed to children in Swift 4.2. See https://developer.apple.com/documentation/uikit/uiviewcontroller/1621452-children?changes=latest_minor

renaming1 renaming2

0
A. Johns On

There are many ways to do this, depending on the interconnectivity of the components, and how tightly you want to bind them. Three examples:

  • Tight binding: The "mother" VC calls a method on the "child" VC, which calls a method on the child View.

  • Loose binding with delegates: Create a delegate protocol, link the child View with the mother VC via this delegate. The mother VC then calls the delegate.

  • Disconnected with notifications: Have the child View listen for a specific "clear" notification. Have the Mother VC post that notification. No direct links between the two.

Pros and cons with each method. The best interaction just depends on your specifics.