从子UIViewController到父UIViewController的通信

4
我还没有解决这个问题:我有一个主视图控制器mainViewController,可以切换两个视图viewControllerA和ViewControllerB。 我通过在mainViewController中放置一个UIButton(mainButton)来切换视图,并单击它可实现viewControllerA <--> ViewControllerB之间的切换。
我的问题在于:我的ViewControllerA有一个UIButton(ButtonA)。 当单击它时,我希望它告诉mainViewController切换到另一个视图(viewControllerB)。
换句话说,子视图(viewControllerA)应向其父视图(mainViewController)发送消息,以表明它想要触发属于主视图而不是自己(viewA)的方法。
请问如何实现这一点?
2个回答

15

当与父对象进行通信时,你有几种设计模式可供选择。委托和通知都是不错的选择。

这里的主要思想是松散耦合的通信。通知使用单例来处理通信,而委托使用弱引用来引用父对象。(查看 Cocoa With Love:避免保留循环

如果你选择委托,你可以为 ViewControllerA 创建一个非正式协议,MainViewController 必须符合该协议。

你可以将其称为 ViewControllerADelegate 协议:

    @protocol ViewControllerADelegate

    @optional
    - (void)bringSubViewControllerToFront:(UIViewController*)aController;

    @end

或者,ViewControllerA可以发布一个通知:

[[NSNotificationCenter defaultCenter] postNotificationName:@"MyFunkyViewSwitcherooNotification" object:self];

如果MainViewController想要知道,它应该监听:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(swapThoseViews:) name:@"MyFunkyViewSwitcherooNotification" object:nil];

我喜欢通知的概念,听起来像是在 .Net 中触发/捕获事件,我回家后会尝试一下。谢谢 Corey! - Yohann T.
可以了。(小错误:在@selector(swapThoseViews:)中去掉“:”) - Yohann T.
为什么苹果自己的文档不能这么简单明了呢? - Wayne Hartman
很棒的东西,我同意:为什么苹果自己的文档不能这么简单明了呢。 - maralbjo
1
如果您不定义协议,则必须导入类头文件,这会耦合类。定义协议可以缓解这种情况。 - Corey Floyd

0
有几种方法可以实现这个目标: 首先,可以查看协议http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocProtocols.html,还可以查看苹果的一些示例项目中使用的RootViewController,例如Metronomehttp://developer.apple.com/iphone/library/samplecode/Metronome/,它用于从主视图切换到偏好设置视图。此外,可以在“View Controller编程指南”中了解模态视图控制器及其交互http://developer.apple.com/iphone/library/featuredarticles/ViewControllerPGforiPhoneOS/PresentingModelViewControllers/PresentingModelViewControllers.html,也可以参考这里的答案Switch between 3 or more views

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接