Home > Mobile >  MacOS-Drag String onto NSStatusItem
MacOS-Drag String onto NSStatusItem

Time:07-02

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

CodePudding user response:

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