ios 使用 Storyboards 以编程方式设置初始视图控制器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10428629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Programmatically set the initial view controller using Storyboards
提问by UserDev
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.
如何以编程方式设置InitialViewController
故事板?我想打开我的故事板到不同的视图,这取决于某些条件可能会因启动而异。
回答by Travis
How to withouta dummy initial view controller
如何没有虚拟初始视图控制器
Ensure all initial view controllers have a Storyboard ID.
确保所有初始视图控制器都有一个 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:
如果您此时运行您的应用程序,您将看到:
Failed to instantiate the default view controller for UIMainStoryboardFile 'MainStoryboard' - perhaps the designated entry point is not set?
And you'll notice that your window property in the app delegate is now nil.
您会注意到应用程序委托中的 window 属性现在为零。
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.
在应用程序的设置中,转到您的目标和Info
选项卡。有明确的值Main storyboard file base name
。在General
选项卡上,清除 的值Main Interface
。这将删除警告。
Create the window and desired initial view controller in the app delegate's application:didFinishLaunchingWithOptions:
method:
在应用程序委托的application:didFinishLaunchingWithOptions:
方法中创建窗口和所需的初始视图控制器:
- (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;
}
回答by Display name
For all the Swiftlovers out there, here is the answer by @Travistranslated into SWIFT:
对于那里的所有Swift爱好者,这是@Travis翻译成SWIFT的答案:
Do what @Travisexplained before the Objective C code. Then,
做@Travis在Objective C 代码之前解释的事情。然后,
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
var exampleViewController: ExampleViewController = mainStoryboard.instantiateViewControllerWithIdentifier("ExampleController") as! ExampleViewController
self.window?.rootViewController = exampleViewController
self.window?.makeKeyAndVisible()
return true
}
The ExampleViewController
would be the new initial view controller you would like to show.
这ExampleViewController
将是您想要显示的新的初始视图控制器。
The steps explained:
步骤说明:
- Create a new window with the size of the current window and set it as our main window
- Instantiate a storyboard that we can use to create our new initial view controller
- Instantiate our new initial view controller based on it's Storyboard ID
- Set our new window's root view controller as our the new controller we just initiated
- Make our new window visible
- 创建一个与当前窗口大小相同的新窗口,并将其设置为我们的主窗口
- 实例化一个故事板,我们可以用它来创建新的初始视图控制器
- 根据 Storyboard ID 实例化我们新的初始视图控制器
- 将我们新窗口的根视图控制器设置为我们刚刚启动的新控制器
- 使我们的新窗口可见
Enjoy and happy programming!
享受和快乐的编程!
回答by Chengjiong
You can programmatically set the key window's rootViewController in (BOOL)application:(UIApplication *)application willFinishLaunchingWithOptions:(NSDictionary *)launchOptions
您可以通过编程方式设置关键窗口的 rootViewController (BOOL)application:(UIApplication *)application willFinishLaunchingWithOptions:(NSDictionary *)launchOptions
for example:
例如:
- (BOOL)application:(UIApplication *)application willFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
if (shouldShowAnotherViewControllerAsRoot) {
UIStoryboard *storyboard = self.window.rootViewController.storyboard;
UIViewController *rootViewController = [storyboard instantiateViewControllerWithIdentifier:@"rootNavigationController"];
self.window.rootViewController = rootViewController;
[self.window makeKeyAndVisible];
}
return YES;
}
回答by MEK
Swift 3:Update to @victor-sigler's code
Swift 3:更新到@victor-sigler 的代码
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
self.window = UIWindow(frame: UIScreen.main.bounds)
// Assuming your storyboard is named "Main"
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
// Add code here (e.g. if/else) to determine which view controller class (chooseViewControllerA or chooseViewControllerB) and storyboard ID (chooseStoryboardA or chooseStoryboardB) to send the user to
if(condition){
let initialViewController: chooseViewControllerA = mainStoryboard.instantiateViewController(withIdentifier: "chooseStoryboardA") as! chooseViewControllerA
self.window?.rootViewController = initialViewController
)
}else{
let initialViewController: chooseViewControllerB = mainStoryboard.instantiateViewController(withIdentifier: "chooseStoryboardB") as! chooseViewControllerB
self.window?.rootViewController = initialViewController
)
self.window?.makeKeyAndVisible(
return true
}
回答by Bhavsar1311
You can set Navigation rootviewcontroller as a main view controller. This idea can use for auto login as per application requirement.
您可以将 Navigation rootviewcontroller 设置为主视图控制器。这个想法可以用于根据应用程序要求自动登录。
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle: nil];
UIViewController viewController = (HomeController*)[mainStoryboard instantiateViewControllerWithIdentifier: @"HomeController"];
UINavigationController navController = [[UINavigationController alloc] initWithRootViewController:viewController];
self.window.rootViewController = navController;
if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_6_1) {
// do stuff for iOS 7 and newer
navController.navigationBar.barTintColor = [UIColor colorWithRed:88/255.0 green:164/255.0 blue:73/255.0 alpha:1.0];
navController.navigationItem.leftBarButtonItem.tintColor = [UIColor colorWithRed:88/255.0 green:164/255.0 blue:73/255.0 alpha:1.0];
navController.navigationBar.tintColor = [UIColor whiteColor];
navController.navigationItem.titleView.tintColor = [UIColor whiteColor];
NSDictionary *titleAttributes =@{
NSFontAttributeName :[UIFont fontWithName:@"Helvetica-Bold" size:14.0],
NSForegroundColorAttributeName : [UIColor whiteColor]
};
navController.navigationBar.titleTextAttributes = titleAttributes;
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
}
else {
// do stuff for older versions than iOS 7
navController.navigationBar.tintColor = [UIColor colorWithRed:88/255.0 green:164/255.0 blue:73/255.0 alpha:1.0];
navController.navigationItem.titleView.tintColor = [UIColor whiteColor];
}
[self.window makeKeyAndVisible];
For StoryboardSegue Users
对于 StoryboardSegue 用户
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle: nil];
// Go to Login Screen of story board with Identifier name : LoginViewController_Identifier
LoginViewController *loginViewController = (LoginViewController*)[mainStoryboard instantiateViewControllerWithIdentifier:@“LoginViewController_Identifier”];
navigationController = [[UINavigationController alloc] initWithRootViewController:testViewController];
self.window.rootViewController = navigationController;
[self.window makeKeyAndVisible];
// Go To Main screen if you are already Logged In Just check your saving credential here
if([SavedpreferenceForLogin] > 0){
[loginViewController performSegueWithIdentifier:@"mainview_action" sender:nil];
}
Thanks
谢谢
回答by m.etka
Open mainstoryboard, select the view that you want start first, then open Utilities--> Attributes. Below the "View Controller" you see the "Is initial View Controller" radio button. Just select it.
打开 mainstoryboard,首先选择你想要启动的视图,然后打开 Utilities--> Attributes。在“视图控制器”下方,您会看到“是初始视图控制器”单选按钮。只需选择它。
--- To the revised question:
--- 对于修改后的问题:
May be you can try this: write a method in ViewDidLoad section of your inital view and when the method runs on application launch, method triggers a segue to another view.
也许你可以试试这个:在你的初始视图的 ViewDidLoad 部分编写一个方法,当该方法在应用程序启动时运行时,方法会触发到另一个视图的转场。
回答by Shmidt
I don't think it's possible. Instead you can have one initial controller which will have segues to different view controllers. On startup, you can decide which segue to perform programmatically.
我不认为这是可能的。相反,您可以拥有一个初始控制器,该控制器将转至不同的视图控制器。在启动时,您可以决定以编程方式执行哪个 segue。
回答by Jayprakash Dubey
You can set initial view controller
using Interface Builder as well as programmatically.
您可以initial view controller
使用 Interface Builder 以及以编程方式进行设置。
Below is approach used for programmatically.
以下是以编程方式使用的方法。
Objective-C :
目标-C:
self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
UIViewController *viewController = [storyboard instantiateViewControllerWithIdentifier:@"HomeViewController"]; // <storyboard id>
self.window.rootViewController = viewController;
[self.window makeKeyAndVisible];
return YES;
Swift :
斯威夫特:
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
var objMainViewController: MainViewController = mainStoryboard.instantiateViewControllerWithIdentifier("MainController") as! MainViewController
self.window?.rootViewController = objMainViewController
self.window?.makeKeyAndVisible()
return true
回答by Nedim Talovic
In AppDelegate.swift
you can add the following code:
在AppDelegate.swift
您可以添加以下代码:
let sb = UIStoryboard(name: "Main", bundle: nil)
let vc = sb.instantiateViewController(withIdentifier: "YourViewController_StorboardID")
self.window?.rootViewController = vc
self.window?.makeKeyAndVisible()
Of course, you need to implement your logic, based on which criteria you'll choose an appropriate view controller.
当然,您需要实现您的逻辑,根据您将选择合适的视图控制器的标准。
Also, don't forget to add an identity (select storyboard -> Controller Scene -> Show the identity inspector -> assign StorboardID).
另外,不要忘记添加一个身份(选择 storyboard -> Controller Scene -> Show the identity inspector ->assign StorboardID)。
回答by Varun Naharia
I created a routing class to handle dynamic navigation and keep clean AppDelegate class, I hope it will help other too.
我创建了一个路由类来处理动态导航并保持干净的 AppDelegate 类,我希望它也能帮助其他人。
//
// Routing.swift
//
//
// Created by Varun Naharia on 02/02/17.
// Copyright ? 2017 TechNaharia. All rights reserved.
//
import Foundation
import UIKit
import CoreLocation
class Routing {
class func decideInitialViewController(window:UIWindow){
let userDefaults = UserDefaults.standard
if((Routing.getUserDefault("isFirstRun")) == nil)
{
Routing.setAnimatedAsInitialViewContoller(window: window)
}
else if((userDefaults.object(forKey: "User")) != nil)
{
Routing.setHomeAsInitialViewContoller(window: window)
}
else
{
Routing.setLoginAsInitialViewContoller(window: window)
}
}
class func setAnimatedAsInitialViewContoller(window:UIWindow) {
Routing.setUserDefault("Yes", KeyToSave: "isFirstRun")
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let animatedViewController: AnimatedViewController = mainStoryboard.instantiateViewController(withIdentifier: "AnimatedViewController") as! AnimatedViewController
window.rootViewController = animatedViewController
window.makeKeyAndVisible()
}
class func setHomeAsInitialViewContoller(window:UIWindow) {
let userDefaults = UserDefaults.standard
let decoded = userDefaults.object(forKey: "User") as! Data
User.currentUser = NSKeyedUnarchiver.unarchiveObject(with: decoded) as! User
if(User.currentUser.userId != nil && User.currentUser.userId != "")
{
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let homeViewController: HomeViewController = mainStoryboard.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController
let loginViewController: UINavigationController = mainStoryboard.instantiateViewController(withIdentifier: "LoginNavigationViewController") as! UINavigationController
loginViewController.viewControllers.append(homeViewController)
window.rootViewController = loginViewController
}
window.makeKeyAndVisible()
}
class func setLoginAsInitialViewContoller(window:UIWindow) {
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let loginViewController: UINavigationController = mainStoryboard.instantiateViewController(withIdentifier: "LoginNavigationViewController") as! UINavigationController
window.rootViewController = loginViewController
window.makeKeyAndVisible()
}
class func setUserDefault(_ ObjectToSave : Any? , KeyToSave : String)
{
let defaults = UserDefaults.standard
if (ObjectToSave != nil)
{
defaults.set(ObjectToSave, forKey: KeyToSave)
}
UserDefaults.standard.synchronize()
}
class func getUserDefault(_ KeyToReturnValye : String) -> Any?
{
let defaults = UserDefaults.standard
if let name = defaults.value(forKey: KeyToReturnValye)
{
return name as Any
}
return nil
}
class func removetUserDefault(_ KeyToRemove : String)
{
let defaults = UserDefaults.standard
defaults.removeObject(forKey: KeyToRemove)
UserDefaults.standard.synchronize()
}
}
And in your AppDelegate call this
在你的 AppDelegate 中调用这个
self.window = UIWindow(frame: UIScreen.main.bounds)
Routing.decideInitialViewController(window: self.window!)