我知道如何在我的MacOS应用程序中拖放图像文件(使用draggingEntered:,prepareForDragOperation:和performDragOperation :)方法。但我无法弄清楚如何对电影文件做同样的事情。这是可能的,如果可以的话怎么办? (如果要查看一些示例代码,将会很有帮助。)
答案 0 :(得分:1)
除了接受的文件成为电影文件外,它基本上应该是相同的。
您的示例代码:
DragContainer.swift文件
import Cocoa
protocol DragContainerDelegate {
func draggingEntered()
func draggingExit()
func draggingFileAccept(_ file: URL)
}
class DragContainer: NSView {
var delegate: DragContainerDelegate?
let acceptTypes = ["mov", "mp4", "avi", "m4v"]
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
setup()
}
required init?(coder decoder: NSCoder) {
super.init(coder: decoder)
setup()
}
func setup(){
registerForDraggedTypes([NSPasteboard.PasteboardType(kUTTypeFileURL as String),
NSPasteboard.PasteboardType(kUTTypeItem as String)])
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
}
override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
delegate?.draggingEntered()
let acceptFiles = checkExtension(sender)
return acceptFiles ? NSDragOperation.generic : NSDragOperation()
}
override func draggingExited(_ sender: NSDraggingInfo?) {
delegate?.draggingExit()
}
override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
if let board = sender.draggingPasteboard().propertyList(forType: NSPasteboard.PasteboardType(rawValue:"NSFilenamesPboardType")) as? [String],
let path = board.first{
let url = URL(fileURLWithPath: path)
delegate?.draggingFileAccept(url)
return true
}
return false
}
func checkExtension(_ draggingInfo: NSDraggingInfo) -> Bool {
if let board = draggingInfo.draggingPasteboard().propertyList(forType: NSPasteboard.PasteboardType(rawValue:"NSFilenamesPboardType")) as? [String],
let path = board.first{
let url = URL(fileURLWithPath: path)
let fileExtension = url.pathExtension.lowercased()
if acceptTypes.contains(fileExtension) {
return true
}
}
return false
}
}
ViewController.swift文件
class ViewController: NSViewController,DragContainerDelegate {
func draggingEntered() {
}
func draggingExit() {
}
func draggingFileAccept(_ file: URL) {
print(file)
// do whatever you want here
}
@IBOutlet weak var dragContainer: DragContainer!
override func viewDidLoad() {
super.viewDidLoad()
dragContainer.delegate = self
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}