Swift PdfKit - UIMenuController show menu when tap on an annotation

189 Views Asked by At

I'm trying to implement a PDF annotation app in which users can highlight text and remove those highlights. I have successfully implemented the highlight function, but I am encountering an issue with the Remove Highlight option not displaying properly in the menu. However, it works if scrolling through the PDF content. Here is how it looks:

enter image description here

This is my implementation:

class PdfAnnotatorView : UIView {
    var pdfView: CustomPdfKit!

    override func becomeFirstResponder() -> Bool {
        return true
    }

    @objc func setSource(_ val: NSString) {
        let url = URL(string: val as String)
        let pdfDoc = PDFDocument(url: url!)!
        self.pdfView.document = pdfDoc
    }

    override func layoutSubviews() {
        pdfView?.frame = self.bounds
    }

    override init (frame : CGRect) {
        super.init(frame: frame)
        self.setupView()
        self.listenForEvents()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.setupView()
        self.listenForEvents()
    }

    @objc private func displayHighlightMenu(){
        let highlightItem = UIMenuItem(title: "Highlight", action: #selector(CustomPdfKit.highlight(_:)))
        UIMenuController.shared.menuItems = [highlightItem]
    }

    private func setupView() {
        pdfView = CustomPdfKit()
        pdfView.autoScales = true
        pdfView.displayMode = .singlePageContinuous
        pdfView.frame = self.bounds
        self.addSubview(pdfView)
    }

    private func listenForEvents() {
        NotificationCenter.default.addObserver(forName: .PDFViewAnnotationHit, object: nil, queue: nil) { (notification) in
            if let annotation = notification.userInfo?["PDFAnnotationHit"] as? PDFAnnotation {
                let highlightItem = MenuItemWithAnnotation(title: "Clear Highlight", action: #selector(CustomPdfKit.clearHighlight), annotation: annotation)
                UIMenuController.shared.menuItems = [highlightItem]
                UIMenuController.shared.setTargetRect(annotation.bounds, in: self)

                if #available(iOS 13.0, *) {
                    UIMenuController.shared.showMenu(from: self.pdfView, rect: annotation.bounds)
                }
                UIMenuController.shared.setMenuVisible(true, animated: false)
            }
        }

        NotificationCenter.default.addObserver(self,
                                               selector: #selector(displayHighlightMenu),
                                               name: .PDFViewSelectionChanged, object: nil)
    }
}


0

There are 0 best solutions below