2013-04-07 59 views
0

RootViewController我有一個按鈕,當它被點擊時使self.navigationController推到CategoryViewController使用委託傳遞值不起作用

然後,在CategoryViewController中,單擊一個單元格推送到SubCatsViewController。當我選擇了一個單元格時,它應該將CategoryViewControllerSubCatsViewController解散回RootViewController

但如何做到這一點?

如果我使用dismissViewControllerAnimated,它只會取消SubCatsViewController而不是CategoryViewController。我在SubCatsViewController中寫了一個代表,所以我可以從SubCatsViewController中獲得選定的值,並且在RootViewController中符合此委託協議,以獲得我想要的值。

但是,我無法使用我寫的委託來獲取值。

- (void)chooseCat:(BButton *)sender 
{ 

    UIStoryboard *storyboard = [UIStoryboard 
    storyboardWithName:@"MainStoryboard_iPhone" bundle:nil]; 
    CategoryViewController *cat = 
    [storyboard instantiateViewControllerWithIdentifier:@"Cats"]; 
    SubCatsViewController *sub = 
    [storyboard instantiateViewControllerWithIdentifier:@"SubCats"]; 
    sub.delegate = self; //correct way? 
    [self.navigationController pushViewController:cat animated:YES]; 
} 

CategoryViewController.m 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath: 
(NSIndexPath *)indexPath 
{ 
    UIStoryboard *storeboard = 
    [UIStoryboard storyboardWithName:@"MainStoryboard_iPhone" bundle:nil]; 
    SubCatsViewController *sub = 
    [storeboard instantiateViewControllerWithIdentifier:@"SubCats"]; 
    sub.subCats = 
    [[self.cats objectAtIndex:indexPath.row] objectForKey:@"subcat"]; 
    [self.navigationController pushViewController:sub animated:YES]; 
} 
SubCatsViewController.h 

@protocol SubCatsDelegate <NSObject> 

- (void)didSelectSubCats:(SubCats *)cats; 

SubCatsViewController.m 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath: 
(NSIndexPath *)indexPath 
{ 
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; 
    cell.accessoryType = UITableViewCellAccessoryCheckmark; 
    self.cat.catId = 
    [[self.subCats objectAtIndex:indexPath.row] objectForKey:@"id"]; 
    self.cat.name = 
    [[self.subCats objectAtIndex:indexPath.row] objectForKey:@"name"]; 
    if ([self.delegate respondsToSelector:@selector(didSelectSubCats:)]) { 
     [self.delegate didSelectSubCats:self.cat]; 
    } 
    [self dismissViewControllerAnimated:YES completion:nil]; 
} 
@end 

回答

0

dismissViewControllerAnimated的文檔:完成:在UIViewController(從中UINavigationController的繼承)說:

所述呈現視圖控制器負責貶呈現的視圖控制器。如果您在呈現的視圖控制器本身上調用此方法,它會自動將該消息轉發給呈現視圖控制器。

這解釋了爲什麼SubCatsViewController(以及只有該視圖控制器)被解僱。 如果RootViewController的確實是你的根視圖控制器,你可以改變你的tableView行:didSelectRowAtIndexPath方法:從

[self dismissViewControllerAnimated:YES completion:nil]; 

[self.navigationController popToRootViewControllerAnimated:YES]; 
+0

這不是根視圖控制器 – 2013-04-10 11:28:32