我需要在启动应用程序时显示不同的UIViewController
。我有一个“登录”页面供用户交互。用户登录或创建帐户后,它将带到另一个UIViewController
并与地图进行交互。我已经上网了,到目前为止,我知道我们应该在AppDelegate.swift
文件中进行操作。由于我仍然遇到一些错误,因此我尚未完成用户是否已登录的声明
AppDelegate
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
Thread.sleep(forTimeInterval: 2.0)
window = UIWindow(frame: UIScreen.main.bounds)
window?.makeKeyAndVisible()
window?.rootViewController = MainNavigationContoller()
return true
}
我还有另一个带有 MainNavigationContoller 的快速文件,该文件应调用mainviewController
override func viewDidLoad() {
super.viewDidLoad()
let isloggedIn = false
if isloggedIn == false {
self.present(mainViewController(), animated: true, completion: nil)
} else {
self.present(mapViewController(), animated: true, completion: nil)
}
}
应用程序通过launchScreen启动,然后将错误发送到mainViewController,例如线程1:致命错误:意外发现nil,同时隐式展开了一个可选值
答案 0 :(得分:0)
您没有正确实例化视图控制器。
这是我用来制作根视图控制器的函数,请将其放入您的AppDelegate中。
YAML
现在在您的Appdelegate中,用以下代码替换您的代码:
func makeRootVC(storyBoardName : String, vcName : String) {
let vc = UIStoryboard(name: storyBoardName, bundle: Bundle.main).instantiateViewController(withIdentifier: vcName)
let nav = UINavigationController(rootViewController: vc)
nav.navigationBar.isHidden = true
self.window?.rootViewController = nav
let options: UIView.AnimationOptions = .transitionCrossDissolve
let duration: TimeInterval = 0.6
UIView.transition(with: self.window!, duration: duration, options: options, animations: {}, completion: nil)
}
}
并在您的MainNavigationController中,
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
Thread.sleep(forTimeInterval: 2.0)
self.makeRootVC(storyboardName: "Main", vcName : "YourVCStoryboardId")
return true
}
注意:打开情节提要,并为每个控制器提供一个StoryboardID。我更喜欢为它们命名与ViewController的名称相同,因为它很容易记住。在vcName中,我们需要传递要呈现的控制器的storyboarID。
更新:
以上代码用于制作根视图控制器,如果要推送控制器,则可以改用以下代码:
override func viewDidLoad() {
super.viewDidLoad()
let isloggedIn = false
let appDelegateObj = UIApplication.shared.delegate as! AppDelegate
if isloggedIn == false {
appDelegateObj.makeRootVC(storyboardName: "Main", vcName: "mainViewController")
} else {
appDelegateObj.makeRootVC(storyboardName: "Main", vcName: "mapViewController")
}
}
在您的MainNavigationController中,如果您不想推动viewDidLoad中的根视图控制器,而只是推入该控制器,则使用上面的代码,如下所示:
extension UIViewController {
func pushVC(storyboardName : String, vcname : String) {
let vc = UIStoryboard.init(name: storyboardName, bundle: Bundle.main).instantiateViewController(withIdentifier: vcname)
vc.hidesBottomBarWhenPushed = true
self.navigationController?.pushViewController(vc, animated: true)
}
}