macOS/Cocoa Drag-n-Drop

Ok… have a partial solution (FINALLY)… the cursor changes, and it picks up the string I want and delivers it to the correct object…
It uses the UIImage of the NSView as the drag item!

In the SOURCE View (in my case an NSVIEW)

  • add NSDraggingSource as a delegate
  • next add registerForDraggedTypes([.string]) in the INIT method
  • finally add
  internal override func mouseDown(with event: NSEvent) {
        self.delegate?.cellClick(self ,index:self.index)
        //
        let pasteboardItem = NSPasteboardItem()
        pasteboardItem.setString(zText!.stringValue, forType:.string)
        let draggingItem = NSDraggingItem(pasteboardWriter: pasteboardItem)
        draggingItem.setDraggingFrame(self.bounds, contents:self)
        beginDraggingSession(with: [draggingItem], event: event, source: self.zIcon.image)
    }

    func draggingSession(_ session: NSDraggingSession, sourceOperationMaskFor context: NSDraggingContext) -> NSDragOperation {
        switch(context) {
        case .withinApplication  : return .generic
        default : return NSDragOperation()
        }
    }

zText! contains the string I want to pass (its different in each instance of the NSVIew

In the DESTINATION (here its a NSSCrollView [for now])

  • add registerForDraggedTypes([.string]) in the INIT method
  • then add
 override func draggingUpdated(_ sender: NSDraggingInfo) -> NSDragOperation { return .copy }
    override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation { return .copy }
    override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
        let droppedString : String = sender.draggingPasteboard.string(forType: .string)!
       let point = convert(sender.draggingLocation, from: nil)
        print("drop=\(droppedString) at \(point))")
        return true
    }
1 Like