pushViewController with tableViewController in viewController

守給你的承諾、 提交于 2019-12-22 18:04:09

问题


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?


回答1:


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.



回答2:


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.



来源:https://stackoverflow.com/questions/2235464/pushviewcontroller-with-tableviewcontroller-in-viewcontroller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!