首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何访问ParentViewController的功能

如何访问ParentViewController的功能
EN

Stack Overflow用户
提问于 2019-02-22 07:19:20
回答 4查看 48关注 0票数 1

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

代码语言:javascript
复制
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”。

代码语言:javascript
复制
class ChildViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        //ParentViewController.needToAccessThisFunction()
    }

}

我怎么能这么做?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2019-02-22 07:40:09

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

一个是使用delegate(我强烈建议使用),而HERE就是这方面的简单例子。

此外,还可以通过在子视图控制器中添加下面的代码直接调用父控件。

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

ViewController中,您需要声明

代码语言:javascript
复制
func methodFromChild() {
    print("call from child")
}
票数 1
EN

Stack Overflow用户

发布于 2019-02-22 07:34:43

你能做到,但这不是个好主意。

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

代码语言:javascript
复制
class ChildViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

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

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

票数 0
EN

Stack Overflow用户

发布于 2019-02-22 07:35:40

代码语言:javascript
复制
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
   }

}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54821958

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档