XCode 4.2: Controlling the Detail View from the Master-Detail Template (iOS 5)
November 11, 2011 16 Comments
In XCode 4.2 (using the iOS 5 SDK), the Master-Detail Application template has replaced the old Split View Application template. Many of the components such as the RootViewController class and the MainWindow.xib no longer exist. The template is much simpler, but it does take some getting use to. The main problem is to control the DetailViewController from the MasterViewController. When running the template without modifications, the MasterViewController only controls itself, and has no control over the DetailViewController. This is a walkthrough of the process of gaining access to the detail side.
Getting Started with the Master-Detail Application Template
1. Start a new project then select the Master-Detail Application Template.
2. For this sample, set the Device Family to iPad and disable the “Use Storyboard”.
3. Run the app in your iPad simulator, and you’ll notice when you click the menu, it only affects itself, not changing the large detail view.
When looking at the code from MasterViewController.h, there is a pointer called detailViewController, this is not a reference to the large detail view in the split view. Instead, it is a reference to the new menu screen that will be pushed on to of the menu table.
Referencing the DetailViewController
At this point there is no way to change anything in the large DetailViewController. This is how you add that reference:
1. Add the following line to the MasterViewController.h file:
@property (strong, nonatomic) DetailViewController *mainDetailViewController;
2. Add the synthesize statement to your MasterViewController.m file:
3. Add the reference to mainDetailViewController from AppDelegate.m:
masterViewController.mainDetailViewController = detailViewController;
4. Now you can start making changes to the large DetailViewController. Let’s change the wording in the label. In the didSelectRowAtIndexPath function in the MasterViewController.m, add the following line:
mainDetailViewController.detailDescriptionLabel.text = @"I did it!";
Now you can run the app, and you will notice that when you press the Detail cell, you will change the text in the main detail view.