Search code examples
objective-cxcodeuitableviewdetailsview

How to Load the Same UIVew with Different Data from a Table List?


I have a small project where I'm trying to build a recipe list for a game. I have my UITableView running great - the only problem is that I don't know how to connect each cell with a DetailView. Currently if you select any of the cells it does the selection animation and goes nowhere.

I also don't know what the best way to approach this would be using the newest iOS5 SDK & Xcode 4.2. I am barely familiar with storyboards but I assume there must be an easier way than creating 40 different DetailViews for each recipe.

My hope was to create a new Recipe.h/Recipe.m Object set and hold all the data in there. Then it could be loaded into the same DetailView template, but the information would change depending on which recipe was selected. I hope this makes sense?

Please let me know if I can clarify anything. I've attached my project source code if this would be helpful... thanks in advance!


Solution

  • First of all, add this piece of code to your MasterViewController.m,

    #import "DetailViewController.h"
    

    Then open your MainStoryboard.storyboard, then follow these steps :

    1. Add a UITableViewCell to the tableview in MasterView.
    2. In the cell's Inspector, select style as Basic, and give its identifier as "Cell".
    3. Control + click the cell and drag a line till DetailView and select Push option. You should be able to see a Storyboard segue. Give its identifier as "showDetail".
    4. Then go to MasterViewController.m and comment the following code in cellForRowAtIndexPath:

      cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

      This is because you are already getting a cell from

      UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    5. Then add the following code in MasterViewController.m

      -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
      {
        if ([segue.identifier isEqualToString:@"showDetail"])
        {
          DetailViewController *dvc = segue.destinationViewController;
          NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
          [dvc setDetailItem:[self.harvestRecipeList objectAtIndex:indexPath.row]];
        }
      }
      

    Build and run. You should be good to go.