4

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.

Giles
  • 1,428
  • 11
  • 21
  • The part about the menu depending on the selection may be about the `autoenabling` feature, however that works. – Fabian Oct 01 '18 at 17:06
  • Thank you @Fabian. I don't want to disable items, I wanted to remove them entirely (or at least hide). I was able to use Willke's solution without having to do any validation - i.e. I left autoenabling on. – Giles Oct 02 '18 at 08:55

1 Answers1

7

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.

Willeke
  • 14,578
  • 4
  • 19
  • 47
  • Thank you very much @Willeke - that got it. I hid all the items I didn't want, recognising them by their .action.description which gave the method name, which I assume is more stable than the title (esp. with localisation etc). – Giles Oct 02 '18 at 08:51
  • For just normal menus, when you sub-class PDFView, you may need to add `, NSMenuItemValidation` to the class declaration. Otherwise, even if you implement `validateMenuItem(...)` it won't get called. – jsbox Nov 28 '20 at 19:55