如何获取拖拽的文件路径
let files = pboard.readObjects(forClasses: [NSURL.self], options: nil) as! [NSURL]
注意获取到的URL和URL.path的不同之处
class FileDragView: NSView {
weak var delegate:FileDragDelegate?
// 注册拖放类型,可以在awakeFromNib中注册
override func awakeFromNib() {
super.awakeFromNib()
// 注册拖放类型
registerForDraggedTypes([.fileURL])
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
// Drawing code here.
}
override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
let sourceDargMask = sender.draggingSourceOperationMask
let pboard = sender.draggingPasteboard
let dragTypes = pboard.types!
if dragTypes.contains(.fileURL) {
if sourceDargMask.contains(NSDragOperation.link) {
return .link
}
if sourceDargMask.contains(.copy) {
return .copy
}
}
return .generic
}
// 注意此处的打印结果
override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
let pboard = sender.draggingPasteboard
let dragTypes = pboard.types!
if dragTypes.contains(.fileURL) {
// 注意使用NSURL而不是URL,因为URL是结构体,在NSURL是class
let files = pboard.readObjects(forClasses: [NSURL.self], options: nil) as! [NSURL]
for fileURL in files {
print("fileURL:\(fileURL)\n,filePath:\(fileURL.path!)")
// fileURL:file:///.file/id=6571367.1690508
//,filePath:/Users/ekko/Documents/Developer/Documents/程序接入H5说明v1.0.html
}
delegate?.didFinishDrag(files[0])
}
return true
}
}
// 拖拽完成的代理
protocol FileDragDelegate:class {
func didFinishDrag(_ fileURL:NSURL)
}
// 在控制器中配置代理,处理拖拽后拿到的文件路径
class DragFileViewController: NSViewController {
@IBOutlet var textView: NSTextView!
@IBOutlet var dragView: FileDragView!
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
dragView.delegate = self
}
}
extension DragFileViewController:FileDragDelegate {
func didFinishDrag(_ fileURL: NSURL) {
do {
let string = try String.init(contentsOf: fileURL as URL, encoding: .utf8)
self.textView.string = string
} catch {
print(error)
}
}
}
网友评论