如何访问ParentViewController的功能

时间:2019-02-22 07:19:20

标签: swift

我在父视图中使用goChildViewController函数切换到ChildViewController。

class ParentViewController: UIViewController {

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

    func goChildViewController() {
        DispatchQueue.main.async {
            self.navigationController?.view.layer.add(CATransition().popFromRight(), forKey: nil)
            self.navigationController?.pushViewController(ChildViewController(), animated: false)
        }
    }

    func needToAccessThisFunction() {
        // I need to call this function from ChildViewController
    }

}

我想从ChildViewController访问功能“ needToAccessThisFunction”。

class ChildViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        //ParentViewController.needToAccessThisFunction()
    }

}

我该怎么做?

4 个答案:

答案 0 :(得分:2)

从子视图控制器调用父级有多种解决方案。

一种方法是使用delegate(我强烈建议),而HERE是简单的例子。

还有另一种方法,您可以在子视图控制器中添加以下代码来直接调用父方法。

@IBAction func btnTapped(_ sender: Any) {
    if let parent = self.parent as? ViewController { //ViewController is a parent view controller here.
        parent.methodFromChild()
    }
}

,在ViewController中,您需要声明

func methodFromChild() {
    print("call from child")
}

答案 1 :(得分:1)

可以这样做,但这不是一个好主意。

您的ChildViewController现在位于导航堆栈中,因此您可以调用父函数,如下所示:

class ChildViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        if let parent = self.navigationController?.viewControllers[0] as? ParentViewController {
            parent.needToAccessThisFunction()
        }
    }
}

这假设ParentViewController位于堆栈的底部(项目[0])。

答案 2 :(得分:1)

Declare protocol to your child controller like this
protocol ChildControllerDeledate: class {
   func callParentFunction()
} 

Then Implement the child protocol in Parent controller 

Extension ParentController: ChildControllerDeledate {

   func callParentFunction() {
     //Call your parent function/method from here
   }

}

答案 3 :(得分:1)

您可以为此使用委托:-

     protocol requiredMethods: class {
           func a()
           func b()
        }

        class FirstVC: UIViewController, requiredMethods {
            func a() {}
            func b() {}


        func goChildViewController() {
                DispatchQueue.main.async {

        let vc = SecondVC()
               vc.delegate = self
               self.navigationController?.view.layer.add(CATransition().popFromRight(), forKey: nil)
                    self.navigationController?.pushViewController(vc, animated: false)
                }
            }

        }

        class SecondVC: UIViewController {
            weak var delegate: requiredMethods?

            // to  call method a() self.delegate?.a())
            // to  call method b() self.delegate?.b())

        }