【问题标题】:Error unwrapping View Controller when called through Appdelegate通过 Appdelegate 调用时解包视图控制器时出错
【发布时间】:2017-12-26 17:10:00
【问题描述】:

所以当应用程序到达前台时,我试图在当前 vc 上显示一个 passwordVC。目前,passcodeVC(我试图在上面展示的 VC)有这个功能:

func present() {
        print("calling present")
        if let passcodeVC = storyboard?.instantiateViewController(withIdentifier: "IdlePasscodeVC") {
        passcodeVC.modalPresentationStyle = .overCurrentContext
        present(passcodeVC, animated: true, completion: nil)
        } else {
            print("there was an error unwrapping")
        }
    }

当应用程序使用此代码到达前台时,我通过 AppDelegate 调用它:

func applicationWillEnterForeground(_ application: UIApplication) { 
        print("app entered foreground")
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    if let passcodeVC = storyboard.instantiateViewController(withIdentifier: "LockVC") as?  IdlePasscodeViewController{
        passcodeVC.present()
    }
    }

修复了一个问题;但现在我收到一个错误“警告:尝试显示其视图不在窗口层次结构中!”

有没有办法解决这个问题?还是有人可以向我展示更好的方法(我已经阅读了通知中心,并且可能有一个听众,但我不知道从哪里开始)。

希望密码 VC 出现在最后打开的屏幕顶部,这样当密码正确时,它可以自行关闭

一种可能的替代方法会有所帮助。

编辑:是否可以使用此解决方案?

Attempt to present ViewController whose view is not in the windows hierarchy

【问题讨论】:

  • 我认为你需要像以前使用故事板一样实例化这个 viewController
  • 我在哪里做呢?在 present() 函数中?
  • IdlePasscodeViewController 是您需要呈现的控制器类型,但是具有present() 方法的viewController 的类是什么?
  • @ReinierMelian 它是一个 UIViewController;你能详细说明一下吗,我有点绿。
  • 当你说 -> let vc = IdlePasscodeViewController() 然后 vc.present() 这个“vc”对象是一个新对象,它没有初始化故事板变量(除非它是计算属性或者你已经以某种方式处理了它。)=>所以你的“故事板”?是零。

标签: ios swift uiviewcontroller viewcontroller appdelegate


【解决方案1】:

检查一下,我认为这可以在某种程度上帮助你

func applicationWillEnterForeground(_ application: UIApplication) { 
        print("app entered foreground")
        let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
        if let passcodeVC = storyboard?.instantiateViewController(withIdentifier: "IdlePasscodeVC") as?  IdlePasscodeViewController{
        passcodeVC.present()
        }
    }

希望对你有帮助

【讨论】:

  • 我收到一条错误消息,提示“使用未解析的标识符 'storyboard”'
  • @BitBeast 再次检查,我假设您的主情节提要称为 Main
  • 是的,我编辑了标识符以使其正确,但现在我收到错误“警告:尝试在 其视图上呈现 不在窗口层次结构中!”
  • 当然,我想说的是,您需要将您的 VC 添加到您的窗口中
  • @BitBeast 在你进入后台之前,你在导航堆栈中有这个 viewController 吗?
猜你喜欢
  • 2017-10-25
  • 2017-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多