Communication from child UIViewController to parent UIViewController

I still do not understand that I have a mainViewController that switches two views, viewControllerA and ViewControllerB. The way I switch the view is to have a UIButton (mainButton) in mainViewController, and clicking on it will switch viewControllerA ↔ ViewControllerB.

Now here is my problem. My ViewControllerA has a UIButton (ButtonA). And I want, by clicking on it, it tells mainViewController to switch to another view (viewControllerB)

In other words, the child view (viewControllerA) should send a message to mainViewController (its parent view) that it wants to run a method that belongs to the main view and not to itself (viewA).

How can I achieve this, please?

+4
source share
2 answers

When communicating with parent objects, you can select several design patterns. Delegation and notification are a good choice.

The big idea here is communication with a free connection. Notifications use Singleton to handle communications, while delegation uses weak references to parent objects. (Check out Cocoa With love: keep cycles )

If you go with a delegation, you can create an unofficial protocol for your ViewControllerA, which the MainViewController must comply with.

You can call it the ViewControllerADelegate protocol:

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

Or ViewControllerA may send a notification:

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

And MainViewController should listen if it wants to know:

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

There are several ways to achieve this: Take a look at the protocols http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocProtocols.html here, also take a look at using RootViewController in some sample projects, Metronome here http://developer.apple.com/iphone/library/samplecode/Metronome/ uses this to switch from the main view to the preference view. Look at the modal view controllers and their interactions in the ViewController programming guide, http://developer.apple.com/iphone/library/featuredarticles/ViewControllerPGforiPhoneOS/PresentingModelViewControllers/PresentingModelViewControllers.html , and you can also see the answers here Switching between 3 or more species

0
source

All Articles