从子uiviewcontroller调用父uiviewcontroller方法 [英] calling a parent uiviewcontroller method from a child uiviewcontroller

查看:361
本文介绍了从子uiviewcontroller调用父uiviewcontroller方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a Parent UIViewController, which opens a child UIViewController:

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

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

I press a Button in the ChildView which should close the the ChildView and call a method in the Parent View:

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

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

How to do that ? I found a good answer (Link to good answer), but I am not sure if this is the best practice with UIViewControllers. Can someone help ?

推荐答案

一种简单的方法可以使用 NSNotificationCenter 为此。

One easy way to achieve this you can use NSNotificationCenter for that.

ParentViewController 中将其添加到 viewDidLoad 方法:

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

之后在 ParentViewController 中添加此函数,当您解除 ChildViewController :

After that add this function in ParentViewController which will get called when you dismiss your ChildViewController:

func refreshList(notification: NSNotification){

    println("parent method is called")
}

并进入你的 ChildViewController 在解除子视图的地方添加此代码:

and into your ChildViewController add this code where you dismissing your child view:

 @IBAction func btnPressed(sender: AnyObject) {

    NSNotificationCenter.defaultCenter().postNotificationName("refresh", object: nil)
    self.dismissViewControllerAnimated(true, completion: nil)
}

现在,当您解除子视图 refreshList 时,将调用该方法。

Now when you dismiss child view refreshList method will be call.

这篇关于从子uiviewcontroller调用父uiviewcontroller方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆