2016-02-25 141 views
0

我有一个视图控制器有两个表视图控制器作为子视图。从表视图(子视图)推新视图控制器

当我点击表格视图控制器中的一个单元格时,我希望它推送到一个新的视图控制器。但是,它说self.navigationControllerself.parentViewController.navigationController(null)

有谁知道我怎么可以从子视图推新视图?谢谢!

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ 
    ProductClass *productClass = [arrProducts objectAtIndex:indexPath.row]; 

    ProductSingleViewController *productSingleViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"ProductSingleViewController"]; 
    productSingleViewController.prod_title = productClass.title; 
    NSLog(@"VC1: %@, VC2: %@", self.navigationController, self.parentViewController.navigationController); 
    [self.parentViewController.navigationController pushViewController:productSingleViewController animated:YES]; 
} 
+0

是您self.parentViewController也为空管理呢? – Husyn

回答

0

处理此问题的一种方法是在UITableViewControllers中设置委托方法。将委托方法添加到您的父视图控制器。只要有人点击表格中的单元格,它就会触发。从这个委托方法你将能够推动一个新的视图控制器到堆栈上。

在MyTableViewController.h:

@protocol MyTableDelegate <NSObject> 
@required 
- (void)selectedCellWithInfo:(NSDictionary *)info 
@end 

@interface MyTableViewController : UITableViewController { 
    id <MyTableDelegate> delegate; 
} 

@property (strong) id delegate; 

在MyTableViewController.m:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
    [delegate selectedCellWithInfo:[myTableDataSource[indexPath.row]]; 
} 

在MyMainViewController.h:

#import "MyTableViewController.h" 

@interface MyMainViewController : UIViewController <MyTableDelegate> 

在MyMainViewController.m:

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    myTableViewController.delegate = self; 
} 

- (void)selectedCellWithInfo:(NSDictionary *)info { 
    // Do something 
} 
0

仅当视图控制器位于导航控制器的导航堆栈中时,视图控制器的navigationController属性才会返回有效的导航控制器对象。

如果PRoductSingleViewController是您的rootviewcontroller 1.拖放导航控制器 2.将导航控制器设置为rootviewcontroller。 3.更换导航孩子的viewController与PRoductSingleViewController

或者你可以在app delegate.m类

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{ 
    _productSingleViewController = [[PRoductSingleViewController alloc]initWithNibName:@"PRoductSingleViewController" bundle:nil]; 
    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController: _productSingleViewController]; 
    [self.window addSubview:navController.view]; 
    [navController release]; 
    [self.window makeKeyAndVisible]; 
    return YES; 
} 
相关问题