【问题标题】:User Defaults Won't Instantiate View Controller用户默认值不会实例化视图控制器
【发布时间】:2021-04-24 05:07:33
【问题描述】:

当用户登录我的应用程序时,将为键“isLogged”保存一个 Swift UserDefault 并设置为 true。如果此 UserDefault 的值为 true,我的目标是让应用程序委托显示不同的视图控制器。

我已经为此苦苦挣扎了好几个星期,因此想看看是否有人知道任何问题。我在 AppDelegate.swift 中调用一个函数来实例化视图控制器,但由于某种原因,视图控制器从未显示。执行了打印语句,所以我知道设置了值,但是为什么没有显示视图控制器?

func application(_ application: UIApplication,
               didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

  checkDefault()

  return true
}

func checkDefault() {
   if (UserDefaults.standard.bool(forKey: "isLogged") == true) {
     print("LoggedIn is true")
     let vc = UIStoryboard(name: "Main", bundle:  
     Bundle.main).instantiateViewController(withIdentifier: 
     "parent_vc") as! ParentHomeViewController

     let navVC = UINavigationController(rootViewController: vc)
     let share = UIApplication.shared.delegate as? AppDelegate
     share?.window?.rootViewController = navVC
     share?.window?.makeKeyAndVisible()
 }
}

谢谢!

【问题讨论】:

  • 为什么不改变视图控制器层次结构?让 ApDelegate 实例化一个 single VC - 就像它通常做的那样 - 并让 那个 根 VC 实例化它需要的东西?
  • 我该怎么做?
  • 请分享您在调试器窗口中得到的信息。

标签: ios swift swift5 appdelegate userdefaults


【解决方案1】:

您应该在SceneDelegate.swift 中致电您的checkDefault()

确切地说,你必须调用函数,

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions)

为了进一步阅读和理解,您可以使用此 https://medium.com/@kalyan.parise/understanding-scene-delegate-app-delegate-7503d48c5445 供参考。

【讨论】:

  • 嗨维韦克,感谢您的回复!我将函数放在 SceneDelegate 中,但是当打开应用程序时,它会将我带到黑屏。我想也许代码正在运行,但由于某种原因它没有得到我想要的视图控制器
  • @astroworld85 你能试试下面的代码吗let navVC = UINavigationController(rootViewController: Controller) navVC.navigationBar.isHidden = true navVC.interactivePopGestureRecognizer?.delegate = Controller as? UIGestureRecognizerDelegate navVC.interactivePopGestureRecognizer?.isEnabled = false self.window?.rootViewController = navigationController self.window?.makeKeyAndVisible()
【解决方案2】:

我已对您的代码进行了一些更改,并且工作正常。

 self.window = UIWindow(frame: UIScreen.main.bounds)

 let storyboard = UIStoryboard(name: "Main", bundle: nil)

 let initialViewController = storyboard.instantiateViewController(withIdentifier: "parent_vc") as! ParentHomeViewController

 let navVC = UINavigationController(rootViewController: initialViewController)
 self.window?.rootViewController = navVC
 self.window?.makeKeyAndVisible()

【讨论】:

  • 感谢德鲁文的回复!我输入了您修改后的代码,但视图控制器仍未实例化。
猜你喜欢
  • 2014-11-07
  • 1970-01-01
  • 2014-07-28
  • 2014-03-17
  • 1970-01-01
  • 1970-01-01
  • 2015-10-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多