xcode – 从AppDelegate(Swift)连接到ViewController

前端之家收集整理的这篇文章主要介绍了xcode – 从AppDelegate(Swift)连接到ViewController前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用标准的 Xcode Swift模板(使用StoryBoards)创建了一个新的OS X Cocoa应用程序.

我已经在AppDelegate.swift中实现了一个IBAction来处理用户何时从“文件菜单中选择“打开…”.如果所选文件是有效的图像文件,我创建一个NSImage,然后我想在ViewController的视图中显示.@H_301_3@

@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中没有窗口这样的东西.@H_301_3@

谢谢,
迈克尔克努森@H_301_3@

解决方法

似乎AppDelegate只能连接到故事板中应用程序场景中的对象.如果要获取ViewController,请从故事板中实例化它.

样品:@H_301_3@

@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
        }
    }
}
原文链接:https://www.f2er.com/iOS/332230.html

猜你在找的iOS相关文章