Search code examples
iosswiftios16ios-pdfkit

How to get rid of "Highlight" context menu item in PDFView?


I'm using PDFKit to render a PDF and I have added custom menus using "UIMenuController". But it is now deprecated from iOS 16 onwards.

I remove share、lookup menu items with code below:

@available(iOS 13.0, *)
open override func buildMenu(with builder: UIMenuBuilder) {
    builder.remove(menu: .lookup)
    builder.remove(menu: .share)
    builder.remove(menu: .replace)
    super.buildMenu(with: builder)
}

But the "Highlight" context menu can't be removed when a user long press to select text in a PDF. There is no way to get rid of this menu item ? And how to use UIEditMenuInteraction in PDFView ?

Any help would be really appreciated.


Solution

  • Use the UIContextMenuInteraction that's available since iOS 13:

    import PDFKit
    
    class ViewController: UIViewController, UIContextMenuInteractionDelegate {
        // ...
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            // Set up the UIContextMenuInteraction for your PDFView
            let interaction = UIContextMenuInteraction(delegate: self)
            pdfView.addInteraction(interaction)
        }
    
        // Implement the UIContextMenuInteractionDelegate method
        func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {
            return UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { _ in
                // Create an empty UIMenu
                return UIMenu(title: "", children: [])
            }
        }
    }