我在Xcode 6中使用下面的代码,我正在使用apple swift为OSx构建一个项目。我没有通常的.m和.h文件,我在这里看到引用。它是一个带有AppDelegate.swift的故事板和每个窗口的类文件。
以下代码从OS X应用程序的主窗口打开一个附加窗口以显示视频。如何存储对新窗口对象的引用,并使用它来从当前窗口执行新窗口内的函数?我试图在原始视图控制器/窗口中创建播放控件来控制新窗口中包含的视频。我知道不同的窗口是不同类别的不同实例,但我仍然试图掌握它们如何能够实时交谈,而不是我看到的一个视图控制器传递信息的大多数示例到同一窗口中包含的另一个视图控制器。
感谢您的帮助!
更新:
答案建议在最初打开窗口的函数内部工作。但是,我无法在不同的功能中访问该方法。我尝试在函数范围之外声明变量,但是我无法访问其他ViewController中的方法
class ViewController: NSViewController {
var MainVideoControllerWindow: NSWindowController?
var MainVideoController: NSViewController?
@IBAction func openPanel(sender: AnyObject) {
if (MainVideoControllerWindow == nil) {
//THIS SECTION WORKS PERFECTLY
let storyboard = NSStoryboard(name: "Main", bundle: nil)
MainVideoControllerWindow = storyboard?.instantiateControllerWithIdentifier("MainVideo") as? NSWindowController
MainVideoControllerWindow!.showWindow(sender)
//THIS LINE WORKS AS SUGGESTED
let MainVideoController = MainVideoControllerWindow!.window?.contentViewController as MainVideo
//I CAN ACCESS THIS METHOD CONTAINED IN OTHER VIEW CONTROLLER
MainVideoController.playVideo(sender)
//TRYING THIS INSTEAD TO ALLOW ACCESS TO OTHER FUNCTIONS WITHIN THIS CLASS
MainVideoController = MainVideoControllerWindow!.window?.contentViewController as MainVideo
//THIS LINE RESULTS IN AN ERROR (NSViewController? does not have a member named playVideo)
MainVideoController.playVideo(sender)
//I TRIED UNWRAPPING IT AND STILL THE SAME ERROR
MainVideoController!.playVideo(sender)
} else {
MainVideoControllerWindow!.showWindow(sender)
}
}
@IBAction func btnPlayVideo(sender: AnyObject) {
//CANNOT ACCESS THE METHOD HERE
MainVideoController.playVideo()
}
}
最终更新:这是允许我从当前窗口中的任何功能访问新Window功能的最终工作代码块。我更改了MainVideoController var声明的类型以匹配我的自定义类,并添加了条件" as?"将contentViewController捕获到变量中时。谢谢@bluedome的帮助!
class ViewController: NSViewController {
var MainVideoControllerWindow: NSWindowController?
var MainVideoController: MainVideo?
@IBAction func openPanel(sender: AnyObject) {
if (MainVideoControllerWindow == nil) {
//OPEN NEW WINDOW
let storyboard = NSStoryboard(name: "Main", bundle: nil)
MainVideoControllerWindow = storyboard?.instantiateControllerWithIdentifier("MainVideo") as? NSWindowController
MainVideoControllerWindow!.showWindow(sender)
//SAVE REFERENCE TO VIEW CONTROLLER IN NEW WINDOW
MainVideoController = MainVideoControllerWindow!.window?.contentViewController as? MainVideo
} else {
MainVideoControllerWindow!.showWindow(sender)
}
}
@IBAction func btnPlayVideo(sender: AnyObject) {
//CAN ACCESS THE METHOD IN OTHER WINDOW'S VIEW CONTROLLER HERE
MainVideoController!.playVideo(sender)
}
}
答案 0 :(得分:4)
您可以NSViewController
NSWindow
contentViewController
获取let viewController = windowController.window?.contentViewController as YourCustomViewController
// do stuff
viewController.method()
。
{{1}}