2016-02-25 143 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; 
} 
相關問題