我有一个父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 ??????怎么做?我找到了一个很好的答案(Link to good answer),但我不确定这是否是UIViewControllers的最佳实践。有人能帮忙吗?
发布于 2015-05-16 10:20:19
实现这一目标的一个简单方法是使用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方法。
发布于 2015-05-16 10:04:05
将弱属性添加到子视图控制器,该子视图控制器应包含对父视图控制器的引用。
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)而且,正如呕吐物所说,在解散您的孩子视图控制器之前,请先调用父母的方法。
parentViewController.someMethod()
self.dismissViewControllerAnimated(true, completion: nil)或者,您也可以在dismissViewControllerAnimated的完成参数中调用该方法,该方法将在您的子视图控制器解除后运行:
self.dismissViewControllerAnimated(true) {
parentViewController.someMethod()
}发布于 2015-05-16 09:40:03
我在您的问题中注意到的一些事情:在退出视图控制器后,不要调用方法(在您的情况下是父方法)。取消视图控制器将导致其被解除分配。以后的命令可能不会执行。
你在问题中包含的链接指向了一个很好的答案。在你的情况下,我会使用授权。在取消子视图控制器之前,在父视图控制器中调用委托方法。
这是一个很好的tutorial。
https://stackoverflow.com/questions/30274017
复制相似问题