gpt4 book ai didi

swift - 如何访问ParentViewController的功能

转载 作者:行者123 更新时间:2023-11-28 05:45:49 25 4
gpt4 key购买 nike

我在父 View 中使用 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()
}

}

我该怎么做?

最佳答案

从 subview Controller 调用父 View 有多种解决方案。

一种是使用delegate(我强烈建议)和HERE就是一个简单的例子。

还有一个可以通过在 subview Controller 中添加以下代码直接调用父级。

@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")
}

关于swift - 如何访问ParentViewController的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54821958/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com