0

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?

Womble Tristes
  • 393
  • 1
  • 4
  • 14

2 Answers2

1

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

André Slotta
  • 13,774
  • 2
  • 22
  • 34
1

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.

A. Johns
  • 199
  • 4