swiftcocoapdfview

How do I customise the contextual menu of a PDFView?


I am using a PDFView instance in my application. I would like to both add my own items to the contextual menu, and remove some default ones that are not suitable within my app.

Some default items are suitable, so ideally I would be adapting the existing menu rather than building a new one.

When I create the pdf view, there is no valid pdfView.menu item in existence, therefore I cannot set my own delegate.

I have tried using a class inheriting from PDFView (which is declared as a NSMenuDelegate) and overriding menuWillOpen and menuNeedsUpdate - but my code is never called.

I can see that the PDFView is blending textfield and pdf related menu items, depending on text selection, in the presented context menu, so there obviously isn't a fixed menu there.

Is there anyway I can intercept this or do I just have to force my own menu on it?

On MacOS 10.13.


Solution

  • Subclass PDFView and override func menu(for event: NSEvent) -> NSMenu?. Call super and adapt the menu.

    Adopt protocol NSMenuItemValidation and implement func validateMenuItem(_ menuItem: NSMenuItem) -> Bool to enable and disable the items.