我想从appdelegate设置初始viewcontroller . 我找到了一个非常好的答案,但它是在Objective C中,我很难在swift中实现同样的功能 .
Programmatically set the initial view controller using Storyboards
- (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;
}
有人能帮忙吗?
我希望初始Viewcontroller依赖于使用条件语句满足的某些条件 .
14 回答
我使用这个线程帮助我将目标C转换为swift,并且它的工作完美 .
Instantiate and Present a viewController in Swift
Swift 2 代码:
Swift 3 代码:
试试这个 . 例如:您应该使用
UINavigationController
作为初始视图控制器 . 然后,您可以从故事板中将任何视图控制器设置为root .见my storyboard screen.
如果你没有使用故事板,你可以试试这个
For Swift 3, Swift 4:
Instantiate root view controller from storyboard:
如果要以root身份使用
UINavigationController
:Instantiate root view controller from xib:
它几乎相同,但不是线条
你必须写
这是接近它的好方法 . 此示例将导航控制器作为根视图控制器放置,并将您选择的视图控制器放在导航堆栈的底部,准备好从中推送您需要的任何内容 .
要使此示例正常工作,您可以在主视图控制器上将“MainViewController”设置为Storyboard ID,在这种情况下,storyboard的文件名将为“MainStoryboard.storyboard” . 我以这种方式重命名我的故事板,因为Main.storyboard对我来说不是一个正确的名称,特别是如果你去它的子类 .
我是在目标上做到的 - 希望它对你有用
对于 swift 4.0 .
在 didfinishedlaunchingWithOptions 方法的 AppDelegate.swift 文件中,输入以下代码 .
希望它能正常工作 .
我在Xcode 8和swift 3.0中做过希望它对你有用,并且它的工作完美 . 使用以下代码:
如果您使用的是导航控制器,请使用以下代码:
Swift 4:
在appDelegate.swift中,在didFinishLaunchingWithOptions()函数中添加这些行...
现在,例如,当我们想要将用户驱动到登录屏幕或初始设置屏幕或返回到应用程序的主屏幕等时,我们多次执行类似这样的操作 . 如果您想要执行类似的操作,你可以把这一点用作叉路 .
想一想 . 你可以在NSUserDefaults中存储一个值,例如持有userLoggedIn布尔值和
if userLoggedIn == false { use this storyboard & initialViewController... } else { use this storyboard & initialViewController... }
那么上面/下面的所有答案都会产生关于故事板中没有入口点的警告 .
如果你想拥有2个(或更多)依赖于某些条件的入口视图控制器(比如conditionVariable),你应该做的是:
在Main.storyboard中创建UINavigationController without rootViewController,将其设置为入口点
创建2(或更多)"Show" segues进入视图控制器,为它们分配一些id,比如说id1和id2
使用下一个代码:
希望这可以帮助 .
Just in case you want to do it in the view controller and not in the app delegate: 只需在视图控制器中获取对AppDelegate的引用并重置它's window object with the right view controller as it' s rootviewController .
这里是Swift 4中的完整解决方案,在didFinishLaunchingWithOptions中实现它
在Appdelegate.swift中的任何位置写这个函数