我正在尝试创建一个播放音频或视频文件的 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/