Swift: Opening a file by drag-and-drop in window

后端 未结 3 2009
傲寒
傲寒 2021-02-06 10:49

In Swift, how can I build an area in a window of my Mac app where a user can drag-and-drop a folder onto this area, and have my app receive the path of the folder?

In pr

3条回答
  •  别跟我提以往
    2021-02-06 11:40

    my 2 cents for OSX - swift 5 (and fixed for loading from XIBs/storybord.)

    //  Created by ing.conti on 31th jan 2020.
    //
    
    import Cocoa
    
    class AnalysisView: NSView {
    
        override init(frame frameRect: NSRect)
        {
            super.init(frame: frameRect)
            self.registerMyTypes()
        }
    
        required init?(coder: NSCoder) {
            super.init(coder: coder)
            self.registerMyTypes()
        }
    
    
        final private func registerMyTypes()
        {
            registerForDraggedTypes(
                [NSPasteboard.PasteboardType.URL,
                 NSPasteboard.PasteboardType.fileURL,
                 NSPasteboard.PasteboardType.png,
                 NSPasteboard.PasteboardType.fileNameType(forPathExtension: "wtf")
            ])
        }
    
    
    
        override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
            print("draggingEntered")
            return NSDragOperation.copy
        }
    
        override func prepareForDragOperation(_ sender: NSDraggingInfo) -> Bool {
            let allow = true // check your types...
            print("prepareForDragOperation")
            return allow
        }
    
        override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
    
            let pasteBoard = sender.draggingPasteboard
            print("performDragOperation")
    
            if let urls = pasteBoard.readObjects(forClasses: [NSURL.self]) as? [URL]{
                // consume them...
                print(urls)
                return true
            }
            return false
        }
    }
    

提交回复
热议问题