xcode Swift:App Delegate 应该如何获得对视图控制器的引用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28662308/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 06:42:36  来源:igfitidea点击:

Swift: How should the App Delegate get a reference to the View Controller?

iosxcodeswift

提问by Alan

I've started a new Swift project, I'm playing around with things to see how the wiring works with storyboards since I've never used them before.

我已经开始了一个新的 Swift 项目,我正在尝试使用故事板来查看接线如何与故事板配合使用,因为我以前从未使用过它们。

The project is a single-view app using the default storyboard created by Xcode 6.1. It generates the AppDelegate.swift and ViewController.swift classes as well as Main.storyboard.

该项目是一个使用 Xcode 6.1 创建的默认故事板的单视图应用程序。它生成 AppDelegate.swift 和 ViewController.swift 类以及 Main.storyboard。

Btw, I'm kind of going off of this tutorial:

顺便说一句,我有点离开本教程:

http://www.raywenderlich.com/74904/swift-tutorial-part-2-simple-ios-app

http://www.raywenderlich.com/74904/swift-tutorial-part-2-simple-ios-app

I've got things working with a button and a couple of textview controls that I added using the storyboard Interface Builder.

我使用故事板界面生成器添加了一个按钮和几个 textview 控件。

What I'd like to do now, is hook up the app delegate's application didFinishLaunchingevent to the view controller.

我现在想做的是将应用程序委托的应用程序 didFinishLaunching事件连接到视图控制器。

func application(application: UIApplication,
     didFinishLaunchingWithOptions launchOptions: 
     [NSObject: AnyObject]?) -> Bool {
}

I've found many StackOverflow articles discussing this, however the examples are all around instantiating your own view controller. I want to simply get a reference to the view controller that was launched via the storyboard.

我发现很多 StackOverflow 文章都在讨论这个,但是这些例子都是关于实例化你自己的视图控制器。我只想获得对通过情节提要启动的视图控制器的引用。

What's the best way to do this? Feel free to point me to the appropriate docs, or other posts.

做到这一点的最佳方法是什么?请随时将我指向适当的文档或其他帖子。

回答by Alan

I finally found this article on checking the current view controller, which had the logic I was looking for:

我终于找到了这篇关于检查当前视图控制器的文章,它具有我正在寻找的逻辑:

var myViewController : ViewController!
...
if let viewControllers = self.window?.rootViewController?.childViewControllers {
    for viewController in viewControllers {
        if viewController.isKindOfClass(ViewController) {
            myViewController = viewController as ViewController
            println("Found the view controller")
        }
    }
}