Search code examples
iphoneuinavigationcontrollerviewtableviewgrouped-table

UITableView Data Based on Previous View


I'm currently working on the settings section of my iPhone app, and I just came to realization that if each page in the settings had it's own view and .h + .m, that would be A LOT of unnecessary code and views. So I came up with the conclusion that I would simply have only one type of detail view that would change depending on the row in a table view that the user selected. However... I'm kind of struggling.

The Setup:

  • For the main settings view, I want it to be a grouped table view with multiple groups and rows.
  • For the settings detail view, I also want it to be a grouped table view with multiple groups and rows (that is where it gets confusing).

I have seen simple things such as images and labels depend on the previous view, but not grouped table view structures. Is it possible to complete what I want without tons of views or 'if' statements? Any sort of help is apreciated.


Solution

  • You'll have to do two things (considering you have a setting view controller and a detail view controller)...

    First, when a user selects a row in the setting view controller, you have to set the setting you'll be editing in the detail view controller. That is....

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
       [self.detailViewCtrl setSetting:[self.settings objectAtIndex:indexPath.row]];
       [self.navigationController pushViewController:self.detailViewCtrl];
    }
    

    In your detail view, you'll have to modify the following method to render your table:

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
      // ... do something with the self.setting
    }
    

    And you can't forget to reload the table:

    - (void)setSetting:(id)newSetting {
      if (setting != newSetting) {
        [setting release];
        setting = [newSetting retain];
        [self.tableView reloadData];
      }
    }
    

    This is assuming the following:

    • Your first view has the 'detailViewCtrl' property instantiated
    • Your first view has an NSArray of settings property called 'settings'
    • Your detail view has a 'setting' property
    • Your detail view controller know what to do with its 'setting' property