美文网首页
如何获取拖拽的文件路径

如何获取拖拽的文件路径

作者: _我和你一样 | 来源:发表于2019-12-13 18:28 被阅读0次

    如何获取拖拽的文件路径

    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)
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:如何获取拖拽的文件路径

          本文链接:https://www.haomeiwen.com/subject/lqcqnctx.html