1

我有使用 storyboard 的导航控制器应用程序的标签栏,
我的目的是在 tab3 中按下一个按钮,在后台我希望 tab1 到“popToRootViewController”

tab3 viewcontroller 中的按钮:

- (IBAction)Action:(id)sender {

    vc1 * first = [[vc1 alloc]init];
    [first performSelector:@selector(popToRootViewController) withObject:Nil];

}

tab1 视图控制器中的代码

-(void)popToRootViewController{

    [self.navigationController popToRootViewControllerAnimated:NO];
    NSLog(@"popToRootViewController");
}

我得到了popToRootViewController日志,但该操作没有执行。

解决问题:

- (IBAction)Action:(id)sender {

        [[self.tabBarController.viewControllers objectAtIndex:0]popToRootViewControllerAnimated:NO];


    }
4

4 回答 4

2

你这样做的方式:

vc1 * first = [[vc1 alloc]init];
[first performSelector:@selector(popToRootViewController) withObject:Nil];

是不正确的。实际上,您在这里创建了一个全新的控制器,完全独立于您现有的控制器,不属于任何导航控制器。为此,self.navigationController在.nilpopToRootViewController

您可以尝试执行以下操作:

 //-- this will give you the left-most controller in your tab bar controller
 vc1 * first = [self.tabBarController.viewControllers objectAtIndex:0];
[first performSelector:@selector(popToRootViewController) withObject:Nil];
于 2014-01-09T10:49:13.527 回答
1

将 TabBar 与 tabBarViewController 绑定 -
在 tabBarViewController.m

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
    NSArray *array = [tabBarController viewControllers];
    if([[array objectAtIndex:tabBarController.selectedIndex] isKindOfClass:[UINavigationController class]])
        [(UINavigationController *)[array objectAtIndex:tabBarController.selectedIndex] popToRootViewControllerAnimated: NO];
}

它对我来说非常有效。

于 2014-01-09T10:55:34.990 回答
1
To press a button in tab3 and in the background I want tab1 to "popToRootViewController"

如果您想popToRootViewController通过按下 tab3 中的按钮在 tab1 中执行,那么我建议您使用NSNotificationCenter. 例如下面的代码: -

在您的firstViewController班级中添加观察者NSNotification

- (void)viewDidLoad
{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(yourMethod:)
                                                name:@"popToRootViewControllerNotification" object:nil];
}

-(void)yourMethod:(NSNotification*)not
{
 [self.navigationController popToRootViewControllerAnimated:NO];
}

在您的ThirdViewController 班级notification中发布以下代码:-

- (IBAction)Action:(id)sender {

 //   vc1 * first = [[vc1 alloc]init];
  //  [first performSelector:@selector(popToRootViewController) withObject:Nil];

//Post your notification here
[[NSNotificationCenter defaultCenter] postNotificationName:@"popToRootViewControllerNotification" object:nil];

}
于 2014-01-09T11:36:15.897 回答
0

如果您的 tab1 和 tab2 在不同的导航控制器中,请在- (IBAction)action:(id)sender

NSArray *viewControllers = [self.tabbarController viewControllers];
for (UIViewController *viewController in viewControllers) {
    if ([viewController isKindOfClass:[vc1 class]]) {
        vc1 * first = (vc1 *) viewController;
        [first.navigationController popToRootViewControllerAnimated:NO];
    }
}
于 2014-01-09T10:53:53.133 回答