Pierre
Pierre

Reputation: 11633

pushViewController with tableViewController in viewController

I have an UIViewController, this controller is contained in a navigationController. I add an UITableViewController in this viewController. I would like to call a pushViewController method when I press on a cell of my tableView.

I tried this :

UITableViewController


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{   
  FirstView *myViewController = [[FirstView alloc] init];
  [f myViewController];
}

UIViewController (FirstView)


-(void)pushIt
{
    SecondView *sCont = [[SecondView alloc] initWithNibName:@"SecondView" bundle:[NSBundle mainBundle]];
    [self.navigationController pushViewController:sCont animated:YES];
    NSLog(@"didSelect"); // is printed
    [sCont release];
    sCont = nil;
}

But nothing happen. I put NSLog() to my pushIt method and I can see it. So I don't understand why I can't push it.

Any idea?

Upvotes: 2

Views: 6826

Answers (2)

Yurii Zhyromskyi
Yurii Zhyromskyi

Reputation: 149

You alloc and init myViewController but never push it to navigation or window or whatever else, then you push sCont to myViewController, that isn't present at window. First, try not using myViewController, next try to push myViewController to navigation before pushing sCont into it.

Upvotes: 0

Jasarien
Jasarien

Reputation: 58448

UIViewController has a property named navigationController that will return a UINavigationController if one exists for the view controller its called from.

Using this property, you can push view controllers onto the navigation stack from your table view's didSelectRowAtIndexPath: method.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{
    SecondView *sCont = [[SecondView alloc] initWithNibName:@"SecondView" bundle:[NSBundle mainBundle]];
    [self.navigationController pushViewController:sCont animated:YES];
    [sCont release];
}

The reason your current code isn't working is probably because of the following:

  • You already have an instance of FirstViewController, as you said you have added a table view as its subview
  • You try and create a new instance of a FirstViewController when the user taps a cell, which isn't on the navigation stack, so trying to push a view controller onto the stack from there doesn't work, because the navigationController property returns nil.

Upvotes: 1

Related Questions