以编程方式设置 rootViewController 不起作用,仅在 Xcode 11 中从情节提要中选择初始视图控制器
Posted
技术标签:
【中文标题】以编程方式设置 rootViewController 不起作用,仅在 Xcode 11 中从情节提要中选择初始视图控制器【英文标题】:Set rootViewController programmatically not working, picking initial view controller from storyboard only in Xcode 11 【发布时间】:2020-01-02 12:38:50 【问题描述】:尝试以编程方式更改根视图控制器,最初在情节提要中检查初始视图控制器。每次打开相同的 viewController 时,它在情节提要中设置为 initialViewController。请指导。在下面分享到目前为止尝试过的代码:
let isLoggedIn = UserDefaults.standard.bool(forKey: kIsLoggedIn)
if isLoggedIn
//Welcome Screen for Touch ID
let storyboard = UIStoryboard(name: "Main", bundle: nil)
// let rootVC = storyboard.instantiateViewController(withIdentifier: "WelcomeViewController") as! WelcomeViewController
let rootVC = storyboard.instantiateViewController(withIdentifier: "DashboardVC") as! DashboardVC
setRoot(rootVC: rootVC)
else
//Login Screen
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let rootVC = storyboard.instantiateViewController(withIdentifier: "RegisterViewController") as! RegisterViewController
setRoot(rootVC: rootVC)
func setRoot(rootVC: UIViewController)
let navController = UINavigationController.init(rootViewController: rootVC)
navController.isNavigationBarHidden = true
//if let window = self.window
window?.rootViewController = rootVC
window?.makeKeyAndVisible()
//
其次,尝试更改 rootViewController 并尝试在登录后添加 MFSideMenu 但无法快速运行。请在下面找到它的代码:
func loadDashBoard(storyboard : UIStoryboard)
let vc = storyboard.instantiateViewController(withIdentifier: "MenuNavigationController")
let sideMenuVC = storyboard.instantiateViewController(withIdentifier: "SideMenuViewController") as! SideMenuViewController
let container : MFSideMenuContainerViewController = MFSideMenuContainerViewController.container(withCenter: vc, leftMenuViewController: sideMenuVC, rightMenuViewController: nil)
let navController = UINavigationController.init(rootViewController: container)
navController.isNavigationBarHidden = true
window?.rootViewController = navController
window?.makeKeyAndVisible()
以上所有编写的代码都在AppDelegate中。
【问题讨论】:
应用代理在 Xcode 11 中没有窗口或根视图控制器。它是场景代理。 【参考方案1】:通过更多的谷歌得到答案,我的意思是***。
class SceneDelegate: UIResponder, UIWindowSceneDelegate
var window: UIWindow?
let storyboard = UIStoryboard(name: "Main", bundle: nil)
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions)
guard let windowScene = scene as? UIWindowScene else return
let vc = storyboard.instantiateViewController (withIdentifier: "Primary") as! ViewController
window = UIWindow(windowScene: windowScene)
window?.rootViewController = vc
window?.makeKeyAndVisible()
SceneDelegate 用于此目的,因为 ios 13 不是 AppDelegate。这是链接SceneDelegate example
【讨论】:
以上是关于以编程方式设置 rootViewController 不起作用,仅在 Xcode 11 中从情节提要中选择初始视图控制器的主要内容,如果未能解决你的问题,请参考以下文章