0

RootViewController我有一个按钮,当它被点击时,它会self.navigationController推动到CategoryViewController.

然后,在 中CategoryViewController,单击一个单元格推送到 SubCatsViewController。当我选择了一个单元格时,它应该解散CategoryViewControllerSubCatsViewController返回RootViewController.

但是怎么做呢?

如果我使用dismissViewControllerAnimated,它只会dismiss,而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
4

1 回答 1

0

DismissViewControllerAnimated:completion: in UIViewController的文档(从 UINavigationController 继承)说:

呈现视图控制器负责关闭它呈现的视图控制器。如果您在呈现的视图控制器本身上调用此方法,它会自动将消息转发到呈现的视图控制器。

这就解释了为什么 SubCatsViewController(并且只有那个视图控制器)被解雇了。如果 RootViewController 确实是您的根视图控制器,您可以更改 tableView:didSelectRowAtIndexPath: 中的行

[self dismissViewControllerAnimated:YES completion:nil];

[self.navigationController popToRootViewControllerAnimated:YES];
于 2013-04-07T12:02:39.827 回答