需要帮助理解 UIViewController 和 UIWindow 初始化

Need help understanding UIViewController and UIWindow initialization

我想知道是否有人可以解释以下代码块,因为我不太理解它。

self.viewController = [[RootViewController alloc] initWithNibName:@"RootViewController" bundle:nil];
self.navigationController = [[ UINavigationController alloc ] initWithRootViewController:self.viewController ];
self.window.rootViewController = self.navigationController;
[self.window makeKeyAndVisible];

然后当你想展示一个新的vc你可以这样做:

OtherViewController *ovc = [[ OtherViewController alloc ] initWithNibName:@"OtherViewController" bundle:nil ];
[ self.navigationController pushViewController:ovc animated:YES ];

要返回,请执行以下操作:

[ self.navigationController popViewControllerAnimated:YES ];

简单的解释。 每个 iOS 应用程序至少有 1 个 UIWindow,它总是需要一个 UIViewController 对象设置为根,这意味着设置为可见的应用程序的初始 ViewController给屏幕上的用户。 而 UINavigationController 是将 ViewController 推入其中的堆栈容器,默认情况下,此摊位中的顶部 ViewController 仅对屏幕可见。但最初它需要一个 UIViewControllerUIWindowUINavigationController's 根视图控制器中设置为根视图控制器,它们需要一个起点。两者的工作方式不同,例如 UIWindow 根视图控制器可以随时更改,但 UINavigationController 不允许我们更改根视图控制器。

现在在你的代码中让我解释一下发生了什么。

self.viewController = [[RootViewController alloc] initWithNibName:@"RootViewController" bundle:nil];
//In Above Line you are loading a UIViewController from a Xib file name RootViewController.xib into viewController property
self.navigationController = [[ UINavigationController alloc ] initWithRootViewController:self.viewController ];
//In Above Line You are allocating a new navigation controller programatically with a root/initial view controller and you are passing your previously loaded view controller to be set as root view controller of this navigation.
self.window.rootViewController = self.navigationController;
//In Above Line You are assigning your navigationController to UIWindow object this means you want your view controllers to be managed in a stack so that if you push a view controller you can snap back easily with a single line of code.
[ self.navigationController popViewControllerAnimated:YES ];
//In This Line you are removing your Top view Controller from a navigation stack Like the Back button does in Setting>General to Setting in iPhone/iPad

导航控制器需要一个 "root" 视图控制器,它是它管理的视图控制器堆栈中的底部视图控制器。

#1 self.viewController = [[RootViewController alloc] initWithNibName:@"RootViewController" bundle:nil];
#2 self.navigationController = [[ UINavigationController alloc ] initWithRootViewController:self.viewController ];
#3 self.window.rootViewController = self.navigationController;
[self.window makeKeyAndVisible];
#4 [self.window makeKeyAndVisible];

第 1 行创建 class "RootViewController" 的视图控制器(必须是自定义视图控制器 class。)它从同名的 nibfile 加载视图控制器的视图.这类似于使用 instantiateViewControllerWithIdentifier 从情节提要中加载视图控制器,不同之处在于您必须指定要创建的视图控制器的 class,以及要加载的 nibfile

第 2 行使用新创建的 "RootViewController" 创建一个导航控制器作为它的根视图控制器

第 3 行将导航控制器安装为应用程序的根视图控制器window。

第 4 行使应用程序 window 处于活动状态 window。