Swift 4: NSFilenamesPboardType not available. What to use instead for registerForDraggedTypes?

后端 未结 7 712
一向
一向 2020-12-28 08:11

After migrating to Swift4 the following code raise compile error:

public final class MediaItemView: NSView {

   public override init(frame frameRect: NSRect         


        
7条回答
  •  既然无缘
    2020-12-28 08:48

    I like the creative workarounds presented here for the deprecated variable NSFilenamesPboardType. After looking into this question, a way to move forward with an equivalent non-deprecated approach is to use readObjects(forClasses:options:). This would also be safer WRT being able to run on future macOSes. It would be implemented like the following example, tested with Swift 4.1, based on having an NSView registered in a storyboard.

    override func awakeFromNib()
    {
        registerForDraggedTypes([.fileURL])
    }
    
    override func draggingEnded(_ sender: NSDraggingInfo)
    {
        sender
            .draggingPasteboard()
            .readObjects(forClasses: [NSURL.self],
                         options: nil)?
            .forEach
            {
                // Do something with the file paths.
                if let url = $0 as? URL { print(url.path) }
            }
    }
    

    Since the class array parameter for readObjects is of type [AnyClass] that is the reason for the use of NSURL instead of URL.

提交回复
热议问题