从AppDelegate(Swift)连接到ViewController [英] Connect to ViewController from AppDelegate (Swift)

查看:418
本文介绍了从AppDelegate(Swift)连接到ViewController的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用标准Xcode Swift模板(使用StoryBoards)创建了一个新的OS X Cocoa应用程序.

I have created a new OS X Cocoa Application using the standard Xcode Swift template (using StoryBoards).

我已经在AppDelegate.swift中实现了一个IBAction来处理用户从文件"菜单中选择打开..."时的情况.如果所选文件是有效的图像文件,则创建一个NSImage,然后将其显示在ViewController的视图中.

I have implemented an IBAction in AppDelegate.swift to handle when the users selects "Open..." from the "File" menu. If the chosen file is a valid image file, I create an NSImage which I then want to display in the view of ViewController.

    @IBAction func openFile(sender: NSMenuItem) {
    var openPanel = NSOpenPanel()
    openPanel.beginWithCompletionHandler { (result :Int) -> Void in
        if result == NSFileHandlingPanelOKButton {
            if let imageURL = openPanel.URL {
                let image = NSImage(contentsOfURL: imageURL)
                // PRESENT image IN THE VIEW CONTROLLER
            }
        }
    }

但是,我看不到从AppDelegate连接到ViewController的任何方法.我只设法找到一些建议,我应该看看self.window!在AppDelegate中,但是在AppDelegate中没有窗口.

However, I don't see any way to connect to ViewController from AppDelegate. I have only managed to find suggestions that I should look at self.window! in AppDelegate, but there is no such thing as a window in AppDelegate.

谢谢, 迈克尔·克努森(Michael Knudsen)

Thanks, Michael Knudsen

推荐答案

似乎AppDelegate只能在情节提要中的Application Scene中连接到对象.如果要获取ViewController,请从情节提要中对其进行实例化.

It seems that AppDelegate can connect to objects only within Application Scene in a storyboard. If you want to get a ViewController, instantiate it from a storyboard.

样本:

@IBAction func menuAction(sender: AnyObject) {
    if let storyboard = NSStoryboard(name: "Main", bundle: nil) {
        let controller = storyboard.instantiateControllerWithIdentifier("VC1") as NSViewController

        if let window = NSApplication.sharedApplication().mainWindow {
            window.contentViewController = controller // just swap
        }
    }
}

这篇关于从AppDelegate(Swift)连接到ViewController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆