在Swift中实现拖放区域

时间:2015-03-24 12:56:23

标签: swift macos cocoa

我最近开始使用Swift构建OS X应用程序,我想知道如何实现拖放区域。

更具体地说,我构建了一个处理图像的应用程序,但目前用户必须手动输入输入图像的路径或使用文件选择器(这非常烦人)。我想改进我的应用程序,允许用户通过简单的拖放输入图像(我只需要检索表示图像路径的字符串)。

我该怎么做?

3 个答案:

答案 0 :(得分:38)

以下是我在应用程序中使用的示例。

  1. 如果需要,将NSDraggingDestination的符合性添加到您的子类声明中(NSImageView不需要,因为它已经符合协议)
  2. 声明接受类型的数组(至少NSFilenamesPboardType
  3. 使用registerForDraggedTypes
  4. 注册这些类型
  5. 覆盖draggingEntereddraggingUpdatedperformDragOperation
  6. 从这些方法中返回NSDragOperation
  7. draggingPasteboard数组
  8. 获取文件路径

    在我的示例中,我添加了一个函数来检查文件扩展名是否属于我们想要的范围。

    Swift 2

    class MyImageView: NSImageView {
    
        override func drawRect(dirtyRect: NSRect) {
            super.drawRect(dirtyRect)
        }
    
        required init?(coder: NSCoder) {
            super.init(coder: coder)
            // Declare and register an array of accepted types
            registerForDraggedTypes([NSFilenamesPboardType, NSURLPboardType, NSPasteboardTypeTIFF])
        }
    
        let fileTypes = ["jpg", "jpeg", "bmp", "png", "gif"]
        var fileTypeIsOk = false
        var droppedFilePath: String?
    
        override func draggingEntered(sender: NSDraggingInfo) -> NSDragOperation {
            if checkExtension(sender) {
               fileTypeIsOk = true
               return .Copy
            } else {
               fileTypeIsOk = false
               return .None
            }
        }
    
        override func draggingUpdated(sender: NSDraggingInfo) -> NSDragOperation {
            if fileTypeIsOk {
                return .Copy
            } else {
                return .None
            }
        }
    
        override func performDragOperation(sender: NSDraggingInfo) -> Bool {
            if let board = sender.draggingPasteboard().propertyListForType("NSFilenamesPboardType") as? NSArray,
                imagePath = board[0] as? String {
                // THIS IS WERE YOU GET THE PATH FOR THE DROPPED FILE
                droppedFilePath = imagePath
                return true
            }
            return false
        }
    
        func checkExtension(drag: NSDraggingInfo) -> Bool {
            if let board = drag.draggingPasteboard().propertyListForType("NSFilenamesPboardType") as? NSArray,
                path = board[0] as? String {
                let url = NSURL(fileURLWithPath: path)
                if let fileExtension = url.pathExtension?.lowercaseString {
                    return fileTypes.contains(fileExtension)
                }
            }
            return false
        }
    }
    

    Swift 3

    class MyImageView: NSImageView {
    
        override func draw(_ dirtyRect: NSRect) {
            super.draw(dirtyRect)
        }
    
        required init?(coder: NSCoder) {
            super.init(coder: coder)
            // Declare and register an array of accepted types
            register(forDraggedTypes: [NSFilenamesPboardType, NSURLPboardType, NSPasteboardTypeTIFF])
        }
    
        let fileTypes = ["jpg", "jpeg", "bmp", "png", "gif"]
        var fileTypeIsOk = false
        var droppedFilePath: String?
    
        override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
            if checkExtension(drag: sender) {
                fileTypeIsOk = true
                return .copy
            } else {
                fileTypeIsOk = false
                return []
            }
        }
    
        override func draggingUpdated(_ sender: NSDraggingInfo) -> NSDragOperation {
            if fileTypeIsOk {
                return .copy
            } else {
                return []
            }
        }
    
        override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
            if let board = sender.draggingPasteboard().propertyList(forType: "NSFilenamesPboardType") as? NSArray,
                imagePath = board[0] as? String {
                // THIS IS WERE YOU GET THE PATH FOR THE DROPPED FILE
                droppedFilePath = imagePath
                return true
            }
            return false
        }
    
        func checkExtension(drag: NSDraggingInfo) -> Bool {
            if let board = drag.draggingPasteboard().propertyList(forType: "NSFilenamesPboardType") as? NSArray,
                path = board[0] as? String {
                let url = NSURL(fileURLWithPath: path)
                if let fileExtension = url.pathExtension?.lowercased() {
                    return fileTypes.contains(fileExtension)
                }
            }
            return false
        }
    }
    

答案 1 :(得分:8)

Swift 4

class MyImageView: NSImageView {

    let NSFilenamesPboardType = NSPasteboard.PasteboardType("NSFilenamesPboardType")

    override func draw(_ dirtyRect: NSRect) {
        super.draw(dirtyRect)
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        // Declare and register an array of accepted types
        registerForDraggedTypes([NSPasteboard.PasteboardType(kUTTypeFileURL as String),
                                 NSPasteboard.PasteboardType(kUTTypeItem as String)])
    }

    let fileTypes = ["jpg", "jpeg", "bmp", "png", "gif"]
    var fileTypeIsOk = false
    var droppedFilePath: String?

    override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
        if checkExtension(drag: sender) {
            fileTypeIsOk = true
            return .copy
        } else {
            fileTypeIsOk = false
            return []
        }
    }

    override func draggingUpdated(_ sender: NSDraggingInfo) -> NSDragOperation {
        if fileTypeIsOk {
            return .copy
        } else {
            return []
        }
    }

    override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
        if let board = sender.draggingPasteboard().propertyList(forType: NSFilenamesPboardType) as? NSArray,
            imagePath = board[0] as? String {
            // THIS IS WERE YOU GET THE PATH FOR THE DROPPED FILE
            droppedFilePath = imagePath
            return true
        }
        return false
    }

    func checkExtension(drag: NSDraggingInfo) -> Bool {
        if let board = drag.draggingPasteboard().propertyList(forType: NSFilenamesPboardType) as? NSArray,
            path = board[0] as? String {
            let url = NSURL(fileURLWithPath: path)
            if let fileExtension = url.pathExtension?.lowercased() {
                return fileTypes.contains(fileExtension)
            }
        }
        return false
    }
}

答案 2 :(得分:0)

此实现允许多个文件

只需在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 = ["pdf"]


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