[英]Is there a way To call a Child UIViewController method from Parent UIViewController?
[英]calling a parent UIViewController method from a child UIViewController
我有一个父 UIViewController,它打开一个子 UIViewController:
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("myChildView") as! UIViewController
self.presentViewController(vc, animated: true, completion: nil)
我按下 ChildView 中的一个按钮,它应该关闭 ChildView 并在父视图中调用一个方法:
self.dismissViewControllerAnimated(true, completion: nil)
CALL PARENTS METHOD ??????
怎么做 ? 我找到了一个很好的答案( 链接到好的答案),但我不确定这是否是 UIViewControllers 的最佳实践。 有人可以帮忙吗?
实现此目的的一种简单方法是使用NSNotificationCenter
。
在您的ParentViewController
添加到viewDidLoad
方法中:
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: Selector(("refresh:")), name:NSNotification.Name(rawValue: "refresh"), object: nil)
}
之后在ParentViewController
中添加这个函数,当你关闭你的ChildViewController
时它会被调用:
func refreshList(notification: NSNotification){
print("parent method is called")
}
并在您的ChildViewController
添加此代码,您可以在其中关闭子视图:
@IBAction func btnPressed(sender: AnyObject) {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "refresh"), object: nil)
self.dismiss(animated: true, completion: nil)
}
现在,当您关闭子视图时,将调用refreshList
方法。
向子视图控制器添加一个弱属性,该属性应包含对父视图控制器的引用
class ChildViewController: UIViewController {
weak var parentViewController: UIViewController?
....
}
然后在你的代码中(我假设它在你的父视图控制器中),
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("myChildView") as! ChildViewController
vc.parentViewController = self
self.presentViewController(vc, animated: true, completion: nil)
而且,正如 vomako 所说,在解除子视图控制器之前调用父方法。
parentViewController.someMethod()
self.dismissViewControllerAnimated(true, completion: nil)
或者,您也可以在dismissViewControllerAnimated的完成参数中调用该方法,它会在您的子视图控制器关闭后运行:
self.dismissViewControllerAnimated(true) {
parentViewController.someMethod()
}
我在您的问题中注意到的一些事情:在解除视图控制器后不要调用方法(在您的情况下为父方法)。 关闭视图控制器将导致它被释放。 以后的命令可能无法执行。
您在问题中包含的链接指向了一个很好的答案。 在你的情况下,我会使用委托。 在关闭子视图控制器之前调用父视图控制器中的委托方法。
这是一个很好的教程。
protocol SampleProtocol
{
func someMethod()
}
class parentViewController: SampleProtocol
{
// Conforming to SampleProtocol
func someMethod() {
}
}
class ChildViewController
{
var delegate:SampleProtocol?
}
self.dismissViewControllerAnimated(true, completion: nil)
delegate?.someMethod()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.