【发布时间】:2015-07-20 22:08:13
【问题描述】:
我有一个 Swift 应用程序,其中包含我想使用this question 中描述的方法保存的数据。现在,我需要知道将这些操作链接到 File -> Save/Save As 菜单项和 File -> Open 菜单项的正确方法是什么。这不是基于文档的应用程序。
我在 OS X 10.10.4 上运行 Xcode 6.4。
【问题讨论】:
标签: swift file file-io menu save
我有一个 Swift 应用程序,其中包含我想使用this question 中描述的方法保存的数据。现在,我需要知道将这些操作链接到 File -> Save/Save As 菜单项和 File -> Open 菜单项的正确方法是什么。这不是基于文档的应用程序。
我在 OS X 10.10.4 上运行 Xcode 6.4。
【问题讨论】:
标签: swift file file-io menu save
创建一个IBAction 函数并通过Interface Builder 将其链接到XIB。
在该函数中创建一个打开/保存面板,让用户选择文件名和位置,使用返回的 NSURL 数组作为保存/加载路径。 (当然是在转换为所需的对象类型之后。)
几乎到处都有很多示例代码,无论是 Objective-C 还是 Swift。
【讨论】:
在 Swift 3 中,这可能看起来很奇怪,因为它使用了“First Responder”,但您所要做的就是将以下代码添加到您的 NSViewController 类中,该类在情节提要上设置为自定义类。它不必像其他@IBAction 函数那样连接。
class Test: NSViewController {
@IBAction func saveDocument(_ sender: Any?) {
// code to execute for save functionality
// following line prints in debug to show function is executing.
// delete print line below when testing is completed.
Print("save")
}
@IBAction func openDocument(_ sender: Any?) {
// code to execute for open functionality here
// following line prints in debug to show function is executing.
// delete print line below when testing is completed.
print("open")
}
}
【讨论】: