使用委托传递值不起作用

时间:2013-04-07 08:51:23

标签: iphone delegates tableview navigationcontroller

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

1 个答案:

答案 0 :(得分:0)

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

  

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

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

[self dismissViewControllerAnimated:YES completion:nil];

[self.navigationController popToRootViewControllerAnimated:YES];
相关问题