허용되는 파일이 동영상 파일이된다는 점을 제외하고는 기본적으로 동일해야합니다. 당신을 위해
예제 코드 :
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.
}
}
}