swift - Xcode:如何创建 View 实例并将信息传递给它们?

标签 swift xcode macos

我正在尝试创建一个播放音频或视频文件的 MacOS 应用程序。我已按照 Apple's website here 上的简单说明进行操作

但我想使用"file">“打开”菜单项调出 NSOpenPanel,并将其传递给 View Controller 。

据推测,打开操作应该在 AppDelegate 中,因为 ViewController 窗口可能未打开。 然后将文件名传递给 ViewController 窗口的新实例。

是吗?如果是这样,我如何从 AppDelegate“调用” View ?

这是 AppDelegate:

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    @IBAction func browseFile(sender: AnyObject) {     
        let dialog = NSOpenPanel();
        if (dialog.runModal() == NSModalResponseOK) {
            let result = dialog.url // Pathname of the file

            if (result != nil) {

            // Pass the filepath to the window view thing.
        } else {
            // User clicked on "Cancel"
            return
        }
        }
    }

这是 ViewController:

class ViewController: NSViewController {
    @IBOutlet weak var playerView: AVPlayerView!  
        override func viewDidLoad() {
            super.viewDidLoad()

            // Get the URL somehow
            let player = AVPlayer(url: url)
            playerView.player = player
        }

最佳答案

你的问题中有一些细节没有透露,但我相信我仍然可以提供正确的答案。

您可以从 AppDelegate 调用 NSOpenPanel,这没什么问题。请注意用户可能会取消对话框以及如何处理这种情况。

考虑到 View ,最好的办法是在 Storyboard 中创建连接到 ViewController(默认情况下是这样)的 WindowController,然后使用 NSStoryBoard.instantiateController(withIdentifier:),然后将其 window 属性与 window.makeKeyAndOrderFront(self) 之类的东西一起使用。如果您的代码中有 NSWindow 或 NSWindowController 类,那么您应该在代码中初始化该类并再次创建窗口键和前端。

关于swift - Xcode:如何创建 View 实例并将信息传递给它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43964287/

相关文章:

postgresql - 如何在我的 Mac 上卸载 postgresql(运行 Snow Leopard)

ios - 动态设置/覆盖本地通知的激活模式

ios - 应用程序在苹果审核时崩溃,但在本地开发时不会崩溃

ios - 如何在swift 3中解析Json对象

ios - swift : Cannot convert value of type '()' to expected argument type '[Double]'

vim 中类似 XCode 的自动完成(没有选项卡)?

ios - 调整 UINavigationController 高度

cocoa - 音频编码: AAC files without the 1/10 second silence at the end of the track

ios - 如何在 UipageViewController swift 中预加载下一个和上一个 View

macos - 如何在无边框窗口中嵌入 NSMenu 以创建假菜单栏