我使用父视图中的ChildViewController函数切换到goChildViewController。
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
}
}我想从needToAccessThisFunction中访问函数“ChildViewController”。
class ChildViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//ParentViewController.needToAccessThisFunction()
}
}我怎么能这么做?
发布于 2019-02-22 07:40:09
有多个解决方案可以从子视图控制器调用父级。
一个是使用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")
}发布于 2019-02-22 07:34:43
你能做到,但这不是个好主意。
您的ChildViewController现在位于导航堆栈上,因此您可以调用父函数如下所示:
class ChildViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let parent = self.navigationController?.viewControllers[0] as? ParentViewController {
parent.needToAccessThisFunction()
}
}
}这假设ParentViewController位于堆栈的底部(item [0])。
发布于 2019-02-22 07:35:40
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
}
}https://stackoverflow.com/questions/54821958
复制相似问题