应用程序将进入后台 – >转到根视图菜单

我正在开发一个有8个视图的应用程序,并使用导航控制器来浏览。 第一个视图是一个主菜单。

我想要的是(每个视图)popup到主视图,如果用户按主页button(应用程序进入后台)。

我知道AppDelegate方法applicationDidEnterBackgroundapplicationWillEnterForeground

我知道从导航控制器调用的方法popToRootViewControllerAnimated

我曾尝试在applicationDidEnterBackground中使用popToRootViewControllerAnimated。 喜欢:

 [self.window.rootViewController.navigationController popToRootViewControllerAnimated:YES]; 

但是这不起作用。

你可以让我知道什么是这份工作的最佳select?

我想你尝试像这样的NSNotificationCenter

applicationDidEnterBackgroundapplicationWillEnterForeground里面放这个

 [[NSNotificationCenter defaultCenter] postNotificationName:@"popToRoot" object:nil]; 

并在你的rootViewController's viewDidLoad (总是出现在应用程序启动)添加此:

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(popToRootViewControllerAnimated) name:@"popToRoot" object:nil]; 

然后在你的rootViewController创build一个方法:

 - (void)popToRootViewControllerAnimated { [self.navigationController popToRootViewControllerAnimated:YES]; } 

每当应用程序首次启动, NSNotificationCenter将初始化名称popToRootpopToRoot准备一个方法popToRootViewControllerAnimated

而当应用程序将进入后台, NSNotificationCenter将传递一个massage @"popToRoot"rootViewController's popToRootViewControllerAnimated方法,并且viewcontroller将会popup到rootview

你有这样的尝试: –

 [self.navigationController popToRootViewControllerAnimated:YES]; 

在这里用navigationControllerreplace你的navigationController名字。

编辑:-

在AppDelegate.h文件中

 @interface AppDelegate : UIResponder <UIApplicationDelegate> { UINavigationController *navMain; } @property (nonatomic, retain) UINavigationController *navMain; 

在AppDelegate.m文件中

 @synthesize navMain; -(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease]; // Override point for customization after application launch. self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil] autorelease]; self.navMain = [[UINavigationController alloc] initWithRootViewController:self.viewController]; self.window.rootViewController = self.navMain; [self.window makeKeyAndVisible]; return YES; } -(void)applicationDidEnterBackground:(UIApplication *)application { NSLog(@"applicationDidEnterBackground"); [self.navMain popToRootViewControllerAnimated:YES]; } 

尝试编辑anwser

在AppDelegate类中为UINavigationController创build一个propery。 在applicationDidEnterBackground:方法中使用UINavigationController属性调用popToRootViewController方法。 假设你的propery名是navigationController那么

  [self.navigationController popToRootViewControllerAnimated:YES]; 

首先:你应该检查rootviewcontroller是否是一个navigationController。 因为self.window.rootViewController.navigationController经常是零。 为什么? 因为navigationController的navigationController是'nil'。 大多数情况下,我将我的rootViewController设置为navigationController

其次:当你的应用程序即将退出时,你不应该做animation的东西。 你应该做不animation

 popToRootViewControllerAnimated:NO