Friday, May 6, 2011

Call UIViewController from "subview"

Hello,

I have a UIViewController which when it loads it loads up this..

MapViewController *mapController = [[MapViewController alloc] initWithNibName:@"MapView" bundle:nil];
    self.mapViewController = mapController;
    [self.view insertSubview:mapController.view atIndex:0];
    [mapController release];

I also have a switch views button that can change to a table view....

if (self.tableViewController ==nil)
    {
     TableViewController *tableController = [[TableViewController alloc] initWithNibName:@"TableView" bundle:nil];
     self.tableViewController = tableController;
    [tableController release];
    //[self.view insertSubview:detailController atIndex:0];
    }

    if (self.mapViewController.view.superview == nil)
    {
     [tableViewController.view removeFromSuperview];
     [self.view insertSubview:mapViewController.view atIndex:0];
    }
    else
    {
     [mapViewController.view removeFromSuperview];
     [self.view insertSubview:tableViewController.view atIndex:0];
    }

I am trying to change the view to a detail view based on selecting a row in the table view and I cannot work out how to call it at all. All methods I have seem to fail! Please help!

From stackoverflow
  • The class you should look at for handling row selection is UITableViewDelegate, which has the method:

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    
  • Add the UITableViewDelegate protocol to your controller class.

    @interface myTableViewController : UITableViewController <UITableViewDelegate>
    

    When you create your table veiw controller set its delegate to be your controller using:

    myTableViewController.delegate = self; // Assuming your setup code runs within the table view controller
    

    In your tableViewController, implement didSelectRowAtIndexPath:

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
    int rowSelected = [indexPath indexAtPosition:0]; // Assuming your UITableView has a single section.
    
    tmadsen : Wouldn't you do indexPath.row to set rowSelected?
    tmadsen : Oh didn't see the comment about the single section there.
    Lee Armstrong : Thanks guys! That worked well, it also turns out I had a SwitchViewController too!

0 comments:

Post a Comment