从子uiviewcontroller调用父uiviewcontroller方法

mcf*_*oft 8 uiviewcontroller ios swift

我有一个Parent UIViewController,它打开一个子UIViewController:

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("myChildView") as! UIViewController
self.presentViewController(vc, animated: true, completion: nil)
Run Code Online (Sandbox Code Playgroud)

我按下ChildView中的一个按钮,它应关闭ChildView并在父视图中调用一个方法:

self.dismissViewControllerAnimated(true, completion: nil)
CALL PARENTS METHOD  ??????
Run Code Online (Sandbox Code Playgroud)

怎么做 ?我找到了一个很好的答案(链接到好的答案),但我不确定这是否是UIViewControllers的最佳实践.有人可以帮忙吗?

Dha*_*esh 14

实现这一目标的一种简单方法就是可以使用NSNotificationCenter它.

在您ParentViewController添加到viewDidLoad方法中:

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

之后添加此函数,ParentViewController当你解雇你的时候会调用它ChildViewController:

func refreshList(notification: NSNotification){

    println("parent method is called")
}
Run Code Online (Sandbox Code Playgroud)

并在您ChildViewController添加此代码时解除您的子视图:

 @IBAction func btnPressed(sender: AnyObject) {

    NSNotificationCenter.defaultCenter().postNotificationName("refresh", object: nil)
    self.dismissViewControllerAnimated(true, completion: nil)
}
Run Code Online (Sandbox Code Playgroud)

现在当你解除子视图refreshList方法时会调用.


chr*_*nse 5

将弱属性添加到应包含对父视图控制器的引用的子视图控制器

class ChildViewController: UIViewController {
weak var parentViewController: UIViewController?
....
}
Run Code Online (Sandbox Code Playgroud)

然后在你的代码中(我假设它在你的父视图控制器内),

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("myChildView") as! ChildViewController
vc.parentViewController = self
self.presentViewController(vc, animated: true, completion: nil)
Run Code Online (Sandbox Code Playgroud)

并且,正如vomako所说,在解雇您的子视图控制器之前调用父方法.

parentViewController.someMethod()
self.dismissViewControllerAnimated(true, completion: nil)
Run Code Online (Sandbox Code Playgroud)

或者,您也可以在dismissViewControllerAnimated的完成参数中调用该方法,在子视图控制器解除之后它将在其中运行:

self.dismissViewControllerAnimated(true) {
    parentViewController.someMethod()
}
Run Code Online (Sandbox Code Playgroud)