iosswiftchildviewcontrollerparentviewcontroller

Call function of child view instance from parent view controller


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?


Solution

  • 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