Yohann T.
Yohann T.

Reputation: 1925

Communication from child UIViewController to parent UIViewController

I haven't figured out that yet: I have a mainViewController that switches two views, viewControllerA and ViewControllerB. The way I switch the view is by having a UIButton (mainButton) in the mainViewController, and clicking on it switches viewControllerA <--> ViewControllerB.

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

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

How could I achieve that please?

Upvotes: 4

Views: 4860

Answers (2)

Corey Floyd
Corey Floyd

Reputation: 25969

When communication to parent objects you have a few design patterns to choose from. Delegation and Notification are both good choices.

The big idea here is communication with loose coupling. Notifications use a Singleton to handle communication while Delegation uses weak references to parent objects. (Check out Cocoa With Love: retain cycles)

If you go with delegation, you can create an informal protocol for your ViewControllerA which MainViewController must conform to.

You may call it the ViewControllerADelegate protocol:

    @protocol ViewControllerADelegate

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

    @end

Or ViewControllerA can post a notification:

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

And MainViewController should be listenting if it wants to know:

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

Upvotes: 15

Daniel
Daniel

Reputation: 22395

There are a few ways to achieve this: Take a look at protocols http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocProtocols.html here, also take a look at the RootViewController use in some of apples sample project, Metronome here http://developer.apple.com/iphone/library/samplecode/Metronome/ is using this to switch from the main view to the preferences view. Look at modal view controllers and their interactions in the View COntroller programing guide, http://developer.apple.com/iphone/library/featuredarticles/ViewControllerPGforiPhoneOS/PresentingModelViewControllers/PresentingModelViewControllers.html and you can also look at the answers here Switch between 3 or more views

Upvotes: 0

Related Questions