从子UIViewController到父UIViewController的通信

问题描述:

我还没有想出:我有一个mainViewController切换两个视图viewControllerA和ViewControllerB。我切换视图的方法是在mainViewController中有一个UIButton(mainButton),然后点击它切换viewControllerA - > ViewControllerB。从子UIViewController到父UIViewController的通信

现在,这是我的问题。我的ViewControllerA有一个UIButton(ButtonA)。而且我想,通过点击它,它告诉mainViewController切换到其他视图(viewControllerB)

换句话说,子视图(viewControllerA)应该将消息发送到mainViewController(其父视图),它想要启动属于主视图的方法,而不是自己(viewA)。

我该怎么做到这一点?

通信时于母公司的对象,你有几个设计图案可供选择的答案。授权和通知都是很好的选择。

这里的大想法是与松耦合的通信。通知使用Singleton来处理通信,而委派对父对象使用弱引用。 (查看爱的可可:retain cycles

如果你与代表团一起去,你可以为你的ViewControllerA创建一个非正式的协议,这个协议必须符合MainViewController。

你可以把它叫做ViewControllerADelegate协议:

@protocol ViewControllerADelegate 

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

    @end 

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

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

而如果想知道MainViewController应listenting:

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

我喜欢通知概念,听起来像.Net中的触发/捕捉事件,当我回家时我会试着去尝试。 Thx Corey! – 2009-08-11 15:40:18

+0

作品。 (小错字:在@selector(swapThoseViews :))中删除“:”。 – 2009-08-14 13:19:48

+0

苹果自己的文档为什么不能这么简单? – 2010-06-11 03:01:42

有几种方式来实现这一目标: 看看协议http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocProtocols.html这里,也看一看在一些苹果样品项目的RootViewController的使用,节拍器这里http://developer.apple.com/iphone/library/samplecode/Metronome/就是采用这种从主视图切换到偏好视图。看看模态视图控制器及其视图控制器编程指南,的互动,您还可以在这里看看Switch between 3 or more views

+0

非常好。 – 2009-08-12 02:19:25