【问题标题】:Access from within AppDelegate the initial view that NavigationController points to从 AppDelegate 中访问 NavigationController 指向的初始视图
【发布时间】:2018-10-19 00:05:18
【问题描述】:

我正在使用 Swift 4,我想知道如何从 AppDelegate 中访问我在故事板中的 NavigationController 指向的初始视图。在这种情况下,它指向的我的初始视图是 HotSpotRISViewController。我需要 AppDelegate 中的 HotSpotRISViewController 实例,以便可以将 url 变量传递给它。我的故事板如下所示:

如何从 AppDelegate 中访问我的 hotSpotRISViewController 实例?我了解委托及其工作原理,并且我了解 AppDelegate 会首先启动应用程序,并可用于各种重要事件,例如应用程序离开前台或在外部打开文本文件时。但是,如果我无法访问当前视图的实例,在这种情况下需要 HotSpotRISViewController (这也是我的 NavigationController 指向的初始视图),我无法对这些事件做任何事情。我猜我以某种方式使用了 window 属性。提前感谢任何可以回答此问题的人。

【问题讨论】:

    标签: ios swift uiviewcontroller uinavigationcontroller appdelegate


    【解决方案1】:

    好的,经过数小时的工作,我解决了它。看看我的 AppDelegate:

    func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any]) -> Bool {
        if let hotSpotRISViewController = UIApplication.shared.keyWindow?.rootViewController?.childViewControllers[0] as? HotSpotRISViewController {
            hotSpotRISViewController.setURL(theURL: url)
        }
    }
    

    或者你可以这样做,我认为这是首选方式:

    func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any]) -> Bool {
        if let hotSpotRISViewController = app.keyWindow?.rootViewController?.childViewControllers[0] as? HotSpotRISViewController {
            hotSpotRISViewController.setURL(theURL: url)
        }
    }
    

    不同之处在于,您使用的是 app.keyWindow,而不是 UIApplication.shared.keyWindow,这似乎更好,因为 app 是您的应用程序的单例,并且在此函数中作为参数传入。

    希望从这个例子中遇到这个问题的任何其他人都可以很好地了解如何找到正确的 ViewController。不要忘记将其转换为 ViewController 的子类,否则您将无法使用您在其中创建的任何功能。

    【讨论】:

      猜你喜欢
      • 2014-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-01
      • 2015-09-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多