0

I am trying to detect when a string is getting dragged onto the NSStatusItem. Here is the implementation of my code in AppDelegate:

func applicationDidFinishLaunching(_ aNotification: Notification) {
         if let button = statusItem.button {
            button.image = NSImage(named:NSImage.Name("StatusBarButtonImage"))
          button.action = #selector(menubarAction(_:))
            button.sendAction(on: [.leftMouseUp, .rightMouseUp])
            button.window?.registerForDraggedTypes([.string ])
            button.window?.delegate = self
        }
    }

And here is my NSWindow delegate calls:

extension AppDelegate:NSWindowDelegate{
    
    func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation{
        NSApplication.shared.activate(ignoringOtherApps: true )

        return .copy
    }
    
    func performDragOperation(_ sender: NSDraggingInfo) -> Bool{
        NSApplication.shared.activate(ignoringOtherApps: true )

        return true
    }
}

However these delegates do not get called when a string is dragged onto the NSStatusItem. I know that drag has been detected as:

applicationDidBecomeActive(_ notification: Notification)

gets called. Any suggestions why my delegate is not getting called.
Thanks
Reza

reza23
  • 3,079
  • 2
  • 27
  • 42

1 Answers1

1

draggingEntered and performDragOperation are methods of protocol NSDraggingDestination. Swift doesn't call a protocol method if the class doesn't adopt the protocol. AppDelegate must adopt NSDraggingDestination.

extension AppDelegate: NSWindowDelegate {
}

extension AppDelegate: NSDraggingDestination {
    
    func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation{
        NSApplication.shared.activate(ignoringOtherApps: true )

        return .copy
    }
    
    func performDragOperation(_ sender: NSDraggingInfo) -> Bool{
        NSApplication.shared.activate(ignoringOtherApps: true )

        return true
    }
}
Willeke
  • 14,578
  • 4
  • 19
  • 47
  • As I can not create a custom window for the button, and NSWindow does allow you to set NSDraggingDestination as a delegate, how can I make the window associated with the button to respond to my implementation of the Drag calls – reza23 Jul 01 '22 at 23:03
  • thanks it worked. I can now see why it does work, but for me, it is not very intuitive. – reza23 Jul 02 '22 at 11:21