如何在 Swift 中的 AppDelegate 中抓取 Viewcontroller

Posted

技术标签:

【中文标题】如何在 Swift 中的 AppDelegate 中抓取 Viewcontroller【英文标题】:How to Grab a Viewcontroller in AppDelegate in Swift 【发布时间】:2019-10-04 06:02:34 【问题描述】:

我打算抛出一个 To Do 应用教程,一切都很顺利,直到我遇到困难,因为教程希望我通过 AppDelegate 获取一个视图控制器。

为了更好地解释它,我开始了一个有趣的个人项目,我想在一个应用程序中添加一些不同的工具。

所以,我通过创建一个 TabBarController 作为我的第一个视图控制器来声明。所以,我可以在不同的 ViewController 上分离每个工具并通过 TabBar 访问它。

虽然 ToDo 应用教程只有一个 NavigationBarController 作为其主 rootViewController,但我丢失了它,因为我无法像教程那样获取所需的 ViewController。

下面我提供了教程与我正在使用的 StoryBoard 一起使用的代表代码。所以,你可以看到我尝试访问的内容。

https://imgur.com/mefbux2 https://imgur.com/ygXru2r

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

        //initialize TaskStore
        let taskStore = TaskStore()

        let todoTasks = [Task(name: "Meditate"), Task(name: "Banana")]
        let doneTasks = [Task(name: "Netflix")]

        taskStore.tasks = [todoTasks, doneTasks]

        //Grab the Tasks Controller
        let tasks = window?.rootViewController?.children.first as? Tasks

        //Set the taskstore accordingly
        tasks?.taskStore = taskStore

        return true
    

Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value

【问题讨论】:

在 AppDelegate 中创建数据并交给视图控制器是没有意义的。将didFinishLaunchingWithOptions除最后一行外的整个正文移动到视图控制器的viewDidLoad 【参考方案1】:

您的 rootViewController 是 UITabBarController,它需要 UIViewController 作为它的子视图(子视图)。

您添加了 UINavigationBarController(它是 VC 的子类)。因此,您拥有的代码将为您提供 NavController 而不是 Tasks。您需要获取 NavController 的子级才能获取任务。

if let navController = window?.rootViewController?.children.first ? UINavigationController 
    let tasks = navController?.children.first ? Tasks 

【讨论】:

谢谢你解释得很好,而且成功了!

以上是关于如何在 Swift 中的 AppDelegate 中抓取 Viewcontroller的主要内容,如果未能解决你的问题,请参考以下文章

如何使用swift获取appdelegate中的当前位置

AppDelegate.swift 如何在 Xcode 6.3 中替换 AppDelegate.h 和 AppDelegate.m

AppDelegate Swift 中的 reloadData

Appdelegate.swift 中的调用函数

AppDelegate 中的 Swift UITabbar 阴影

Swift:从 AppDelegate 中的 UNTextInputNotificationAction 获取内容