AppDelegate 中可以 navigation push 吗
时间: 2024-03-12 21:43:53 浏览: 17
在 `AppDelegate` 中也可以使用 `UINavigationController` 进行页面的跳转,但是这不是一个好的编程实践,因为 `AppDelegate` 主要负责应用程序的生命周期和应用级别的事件处理,不应该直接处理视图控制器的跳转逻辑。
如果需要在 `AppDelegate` 中进行页面跳转,可以通过获取 `UIWindow` 的 `rootViewController` 属性来获取当前的根视图控制器,然后进行跳转。例如:
```objective-c
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// 创建 UIWindow 实例
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
// 创建根视图控制器
UIViewController *rootViewController = [[UIViewController alloc] init];
rootViewController.view.backgroundColor = [UIColor whiteColor];
// 创建 UINavigationController 实例,并设置根视图控制器
UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:rootViewController];
// 将 UINavigationController 实例设置为 UIWindow 的根视图控制器
self.window.rootViewController = navigationController;
// 显示窗口
[self.window makeKeyAndVisible];
// 在需要的地方进行页面跳转
UIViewController *targetViewController = [[UIViewController alloc] init];
[navigationController pushViewController:targetViewController animated:YES];
return YES;
}
```
这样做虽然可以实现页面的跳转,但是建议还是在视图控制器中进行页面跳转,这样代码更加清晰,也符合 MVC 设计模式的思想。