Call function from child to parent in Swift

1.9k views Asked by At

I am using xlpagertabstrip and I have a parent view controller which has two children (child1, child2).

In my parent view controller, I show a UIActivityViewIndicator but I want to know how to hide that indicator in my child1.

This is my code:

ParentViewController:

override func viewDidLoad() {
       showActivityIndicator()
       super.viewDidLoad()
}

func showActivityIndicator() {
    //code related to titleview
    navigationItem.titleView = titleView
}

func hideActivityIndicator() {
    navigationItem.titleView = nil
}

Child1ViewController:

override func viewDidLoad() {
    super.viewDidLoad()
    call_api()
}

func call_api(){
    //code related to api
    //if api is ok, I call hideActivityIndicator()
    let pctrl = ParentViewController()
    pctrl.hideActivityIndicator()
}

But that code does not work. How can I solve that?

2

There are 2 answers

12
Pato Salazar On

Just pass hideActivityIndicator() from the parent to the child and call it when necessary. So whenever you create your child controller do this:

// Parent Controller

childVC.someMethodFromParent = hideActivityIndicator

And in your ChildController do this:

// Child Controller

internal var someProperty: (() -> Void)!

override func viewDidLoad() {
    super.viewDidLoad()
    call_api()
}

func call_api(){
    //code related to api
    //if api is ok, I call hideActivityIndicator()

   someMethodFromParent()
}

This should work

4
Sunil Chauhan On

How about having a ChildViewControllerDelegate? Something like:

class ParentViewController {
    func someFunc(){
        ...
        childVC.delegate = self
        ...
    }
}

extension ParentViewController: ChildViewControllerDelegate {
    func childViewControllerDidFinishApiCall() {
        hideActivityIndicator()
    }
}

protocol ChildViewControllerDelegate: class {
    func childViewControllerDidFinishApiCall()
}

class ChildViewController {
    weak var delegate: ChildViewControllerDelegate?

    func call_api(){
        //code related to api
        let pctrl = ParentViewController()
        delegate?.childViewControllerDidFinishApiCall()
    }
}