【发布时间】:2020-01-12 07:29:33
【问题描述】:
我正在尝试将文件从 NSTableView 拖放到 Finder 上。当我尝试拖动一行时,除了向下拖动表格时会选择多行之外,什么也没有发生。我的表的初始化代码是:
filesList.delegate = self
filesList.dataSource = self
filesList.doubleAction = #selector(doubleClick)
filesList.registerForDraggedTypes([.fileURL])
let descriptorName = NSSortDescriptor(key: "name", ascending: true)
let descriptorSize = NSSortDescriptor(key: "size", ascending: true)
let descriptorAttr = NSSortDescriptor(key: "attr", ascending: true)
filesList.tableColumns[0].sortDescriptorPrototype = descriptorName
filesList.tableColumns[1].sortDescriptorPrototype = descriptorSize
filesList.tableColumns[2].sortDescriptorPrototype = descriptorAttr
filesList.setDraggingSourceOperationMask([.copy], forLocal: false)
稍后,我有这段代码,现在并没有做太多。我希望这会给我放置的文件夹的路径。
func tableView(_ tableView: NSTableView, writeRowsWith rowIndexes: IndexSet, to pboard: NSPasteboard) -> Bool {
guard let board = pboard.propertyList(forType: NSPasteboard.PasteboardType(rawValue: "NSFilesPromisePboardType ")) as? NSArray,
let path = board[0] as? String
else { return false }
print(path)
return true
}
更新 感谢 Willeke 下面的提示,我几乎可以让它工作。以下是我的更新代码:
func tableView(_ tableView: NSTableView,pasteboardWriterForRow row: Int)-> NSPasteboardWriting?
{
var filePaths = [String]()
let item = NSPasteboardItem()
let folderPath = URL(fileURLWithPath: NSTemporaryDirectory())
let toPath = folderPath.absoluteString.replacingOccurrences(of: "file://", with: "")
for (_, index) in filesList.selectedRowIndexes.enumerated() {
var fileName = files[index].name
if self.dirPath != "" {
fileName = "\(self.dirPath)/\(fileName)"
}
let command="\"\(getImgTool())\" get \(self.format) \"\(self.path)\" \"\(fileName)\" \"\(toPath)\(fileName)\""
// let command = "cd ~; \(self.getImgTool()) put \(self.format) \(self.path) \(fileName) \(filePath)"
let _ = shell(command)
filePaths.append("\(toPath)\(fileName)")
}
item.setPropertyList(filePaths, forType: .fileURL)
return item
}
我现在遇到的问题是 Finder 不接受丢弃。 Xcode 报告“风味 public.file-url 立即需要沙盒扩展数据,但未能获取。”所以,我将 .fileURL 更改为 .URL 并且 Finder 接受它,但文件没有被写入/复制。我错过了什么?
【问题讨论】:
-
提示:使用
tableView(_:pasteboardWriterForRow:)而不是tableView(_:writeRowsWith:to:)并返回url。 -
更多提示:为
row行的项目返回URL,而不是所有选定行的列表。使用URL方法而不是路径字符串来构造URL。
标签: swift macos drag-and-drop nstableview