我有使用故事板的导航控制器应用程序的标签栏,
我的目的是按下tab3中的按钮,在后台我想要tab1到“popToRootViewController”
tab3 viewcontroller中的按钮:
- (IBAction)Action:(id)sender {
vc1 * first = [[vc1 alloc]init];
[first performSelector:@selector(popToRootViewController) withObject:Nil];
}
tab1 viewcontroller中的代码
-(void)popToRootViewController{
[self.navigationController popToRootViewControllerAnimated:NO];
NSLog(@"popToRootViewController");
}
我在日志中获得popToRootViewController
,但操作未执行。
:
- (IBAction)Action:(id)sender {
[[self.tabBarController.viewControllers objectAtIndex:0]popToRootViewControllerAnimated:NO];
}
答案 0 :(得分:2)
你这样做的方式:
vc1 * first = [[vc1 alloc]init];
[first performSelector:@selector(popToRootViewController) withObject:Nil];
不正确。实际上,您在这里创建了一个全新的控制器,完全独立于现有的控制器,不属于任何导航控制器。因此,self.navigationController
中的nil
为popToRootViewController
。
您可以尝试执行以下操作:
//-- 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];
答案 1 :(得分:1)
使用tabBarViewController绑定TabBar-
在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];
}
它非常适合我。
答案 2 :(得分:1)
To press a button in tab3 and in the background I want tab1 to "popToRootViewController"
如果您想通过按Tab3中的按钮在tab1中执行popToRootViewController
,那么我想建议使用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];
}
答案 3 :(得分:0)
如果您的tab1和tab2位于不同的navigationController中,请在- (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];
}
}