从子 UIViewController 调用父 UIViewController 方法

2024-03-20

我有一个父 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  ??????

怎么做 ? 我找到了一个很好的答案(链接到好答案 https://stackoverflow.com/questions/28427977/call-parentcontroller-method-from-childcontroller-in-swift),但我不确定这是否是 UIViewController 的最佳实践。有人可以帮忙吗?


您可以使用一种简单的方法来实现这一目标NSNotificationCenter为了那个原因。

In your ParentViewController将其添加到viewDidLoad method:

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方法将被调用。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从子 UIViewController 调用父 UIViewController 方法 的相关文章

随机推荐