os x Swift:使用拖放获取文件路径

时间:2015-07-27 15:45:43

标签: xcode macos swift cocoa

如何在swift 2.0中实现拖放区域?

我构建了一个处理kext文件的应用程序但是,现在,我必须手动输入输入kext的路径。 我的问题是:如何通过在区域上执行拖放来获取文件路径?

2 个答案:

答案 0 :(得分:27)

[更新到Swift 4.0和Xcode 9]

将NSView添加到主视图和子类中。 此代码在Swift 4.0和macOS 10.13 High Sierra中完美运行!

import Cocoa

class DropView: NSView {

    var filePath: String?
    let expectedExt = ["kext"]  //file extensions allowed for Drag&Drop (example: "jpg","png","docx", etc..)

    required init?(coder: NSCoder) {
        super.init(coder: coder)

        self.wantsLayer = true
        self.layer?.backgroundColor = NSColor.gray.cgColor

        registerForDraggedTypes([NSPasteboard.PasteboardType.URL, NSPasteboard.PasteboardType.fileURL])
    }

    override func draw(_ dirtyRect: NSRect) {
        super.draw(dirtyRect)
        // Drawing code here.
    }

    override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
        if checkExtension(sender) == true {
            self.layer?.backgroundColor = NSColor.blue.cgColor
            return .copy
        } else {
            return NSDragOperation()
        }
    }

    fileprivate func checkExtension(_ drag: NSDraggingInfo) -> Bool {
        guard let board = drag.draggingPasteboard().propertyList(forType: NSPasteboard.PasteboardType(rawValue: "NSFilenamesPboardType")) as? NSArray,
              let path = board[0] as? String
        else { return false }

        let suffix = URL(fileURLWithPath: path).pathExtension
        for ext in self.expectedExt {
            if ext.lowercased() == suffix {
                return true
            }
        }
        return false
    }

    override func draggingExited(_ sender: NSDraggingInfo?) {
        self.layer?.backgroundColor = NSColor.gray.cgColor
    }

    override func draggingEnded(_ sender: NSDraggingInfo) {
        self.layer?.backgroundColor = NSColor.gray.cgColor
    }

    override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
        guard let pasteboard = sender.draggingPasteboard().propertyList(forType: NSPasteboard.PasteboardType(rawValue: "NSFilenamesPboardType")) as? NSArray,
              let path = pasteboard[0] as? String
        else { return false }

        //GET YOUR FILE PATH !!!
        self.filePath = path
        Swift.print("FilePath: \(path)")

        return true
    }
}

要使用此代码,您必须将“macOS Deployment Target”设置为10.13

screenshot

答案 1 :(得分:1)

此实现允许多个文件

只需在Interface Builder中将视图类设置为DragView,在您的控制器中实现DragViewDelegate,然后在Interface Builder中连接委托出口即可。这样,您将获得带有文件URL的委托回调。

func dragViewDidReceive(fileURLs: [URL])
{
    // Yay!
}

DragView.swift

//
//  DragView.swift
//
//  Copyright (c) 2020 Geri Borbás http://www.twitter.com/_eppz
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import Cocoa


@objc protocol DragViewDelegate
{


    func dragViewDidReceive(fileURLs: [URL])
}


class DragView: NSView
{


    @IBOutlet weak var delegate: DragViewDelegate?
    let fileExtensions = ["kext"]


    required init?(coder: NSCoder)
    {
        super.init(coder: coder)
        color(to: .clear)
        registerForDraggedTypes([.fileURL])
    }

    override func draggingEntered(_ draggingInfo: NSDraggingInfo) -> NSDragOperation
    {
        var containsMatchingFiles = false
        draggingInfo.draggingPasteboard.readObjects(forClasses: [NSURL.self], options: nil)?.forEach
        {
            eachObject in
            if let eachURL = eachObject as? URL
            {
                containsMatchingFiles = containsMatchingFiles || fileExtensions.contains(eachURL.pathExtension.lowercased())
                if containsMatchingFiles { print(eachURL.path) }
            }
        }

        switch (containsMatchingFiles)
        {
            case true:
                color(to: .secondaryLabelColor)
                return .copy
            case false:
                color(to: .disabledControlTextColor)
                return .init()
        }
    }

    override func performDragOperation(_ draggingInfo: NSDraggingInfo) -> Bool
    {
        // Collect URLs.
        var matchingFileURLs: [URL] = []
        draggingInfo.draggingPasteboard.readObjects(forClasses: [NSURL.self], options: nil)?.forEach
        {
            eachObject in
            if
                let eachURL = eachObject as? URL,
                fileExtensions.contains(eachURL.pathExtension.lowercased())
            { matchingFileURLs.append(eachURL) }
        }

        // Only if any,
        guard matchingFileURLs.count > 0
        else { return false }

        // Pass to delegate.
        delegate?.dragViewDidReceive(fileURLs: matchingFileURLs)
        return true
    }

    override func draggingExited(_ sender: NSDraggingInfo?)
    { color(to: .clear) }

    override func draggingEnded(_ sender: NSDraggingInfo)
    { color(to: .clear) }

}


extension DragView
{


    func color(to color: NSColor)
    {
        self.wantsLayer = true
        self.layer?.backgroundColor = color.cgColor
    }
}