使用 Storyboards 以编程方式设置初始视图控制器 [英] Programmatically set the initial view controller using Storyboards
问题描述
如何以编程方式设置故事板的 InitialViewController
?我想根据某些条件(可能因发布而异)将故事板打开到不同的视图.
How do I programmatically set the InitialViewController
for a Storyboard? I want to open my storyboard to a different view depending on some condition which may vary from launch to launch.
推荐答案
如何没有一个虚拟的初始视图控制器
How to without a dummy initial view controller
确保所有初始视图控制器都有一个 Storyboard ID.
Ensure all initial view controllers have a Storyboard ID.
在故事板中,取消选中是初始视图控制器";来自第一个视图控制器的属性.
In the storyboard, uncheck the "Is initial View Controller" attribute from the first view controller.
如果您此时运行您的应用您会读:
If you run your app at this point you'll read:
未能为 UIMainStoryboardFile 'MainStoryboard' 实例化默认视图控制器 - 可能指定的入口点未设置?
Failed to instantiate the default view controller for UIMainStoryboardFile 'MainStoryboard' - perhaps the designated entry point is not set?
您会注意到应用程序委托中的 window 属性现在为零.
And you'll notice that your window property in the app delegate is now nil.
在应用程序的设置中,转到您的目标和 Info
标签.清除Main storyboard file base name
的值.在 General
选项卡上,清除 Main Interface
的值.这将删除警告.
In the app's setting, go to your target and the Info
tab. There clear the value of Main storyboard file base name
. On the General
tab, clear the value for Main Interface
. This will remove the warning.
在应用程序委托的application:didFinishLaunchingWithOptions:
方法中创建窗口和所需的初始视图控制器:
Create the window and desired initial view controller in the app delegate's application:didFinishLaunchingWithOptions:
method:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
UIViewController *viewController = // determine the initial view controller here and instantiate it with [storyboard instantiateViewControllerWithIdentifier:<storyboard id>];
self.window.rootViewController = viewController;
[self.window makeKeyAndVisible];
return YES;
}
这篇关于使用 Storyboards 以编程方式设置初始视图控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!