2

我有一個UIViewController,這個控制器包含在一個navigationController中。 我在這個viewController中添加一個UITableViewController。當我按下tableView的單元格時,我想調用pushViewController方法。pushViewController with tableViewController in viewController

我嘗試這樣做:

的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; 
} 

但沒有發生。我把NSLog()放到了我的pushIt方法中,我可以看到它。所以我不明白爲什麼我不能推它。

任何想法?

+0

反正什麼? – willcodejavaforfood 2010-02-10 09:33:55

+0

Oups我將f更改爲myViewController var name以獲得更多理解,但我忘記在我的調用中更改它。所以:[myViewController pushIt] – Pierre 2010-02-10 11:55:30

回答

1

UIViewController有一個名爲navigationController的屬性,如果存在一個名爲from的視圖控制器,將返回UINavigationController

使用此屬性,可以將視圖控制器從表視圖的didSelectRowAtIndexPath:方法推送到導航堆棧上。

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

當前的代碼是不工作的原因是因爲大概如下:

  • 您已經FirstViewController的實例,如你所說,你已經添加了一個表視圖,其子視圖
  • 當用戶點擊不在導航堆棧上的單元格時,您嘗試創建FirstViewController的新實例,因此嘗試從此處將視圖控制器推入堆棧不起作用,因爲navigationController屬性返回零。
+0

感謝您的答案。 Jasarien,我把你的代碼,但沒有任何反應。這很奇怪... – Pierre 2010-02-10 09:39:19

+0

這是因爲你的表視圖控制器不是導航堆棧的一部分。它的視圖僅作爲FirstViewController視圖的子視圖添加。爲什麼表視圖控制器不是根視圖控制器的原因是什麼?您的FirstViewController是否包含除表格視圖以外的UI? – Jasarien 2010-02-10 09:48:36

+0

哼,不,但我想自定義我的視圖只是爲了修復元素,例如:table.view.frame = CGRectMake(20,20,300,300); 並自定義它周圍的所有元素(例如圖像)。 – Pierre 2010-02-10 11:11:27

0

你的alloc和init myViewController但從來沒有把它推到導航或窗口或任何其他,那麼你推到SCONT myViewController,這是不存在的窗口。首先,不要嘗試使用myViewController,接下來嘗試將myViewController推送到導航,然後再將sCont推入它。