从一个子uiviewcontroller调用一个父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中按下一个Button应该closuresChildView并在父视图中调用一个方法:

 self.dismissViewControllerAnimated(true, completion: nil) CALL PARENTS METHOD ?????? 

怎么做 ? 我发现一个很好的答案( 链接到良好的答案 ),但我不知道这是否与UIViewControllers的最佳做法。 有人可以帮忙吗?

一个简单的方法来实现这一点,你可以使用NSNotificationCenter的。

在你的ParentViewController添加这个viewDidLoad方法:

 override func viewDidLoad() { super.viewDidLoad() NSNotificationCenter.defaultCenter().addObserver(self, selector: "refreshList:", name:"refresh", object: nil) } 

之后在ParentViewController中添加这个函数,当你closures你的ChildViewController时候会调用它:

 func refreshList(notification: NSNotification){ println("parent method is called") } 

并进入你的ChildViewController添加这个代码你解雇你的子视图:

  @IBAction func btnPressed(sender: AnyObject) { NSNotificationCenter.defaultCenter().postNotificationName("refresh", object: nil) self.dismissViewControllerAnimated(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的完成参数中调用该方法,在子视图控制器closures之后 ,将在该参数中运行该方法:

 self.dismissViewControllerAnimated(true) { parentViewController.someMethod() } 

我在你的问题中注意到的一些事情:closures视图控制器之后,不要调用方法(在你的情况下是父方法)。 closures视图控制器将导致它被解除分配。 稍后的命令可能不会被执行。

您在问题中包含的链接指向一个很好的答案。 就你而言,我会用代表团。 在closures子视图控制器之前,调用父视图控制器中的委派方法。

这是一个很好的教程 。

 protocol SampleProtocol { func someMethod() } class parentViewController: SampleProtocol { // Conforming to SampleProtocol func someMethod() { } } class ChildViewController { var delegate:SampleProtocol? } self.dismissViewControllerAnimated(true, completion: nil) delegate?.someMethod()