UIMenuController show other option after another

68 Views Asked by At

I'm currently working on a feature that allows users to highlight text on a PDF document using PdfKit. There is a requirement that after selecting "Highlight" option from menu, users should be able to perform additional actions. Specifically, a different menu should appear with an option called "Another." However, I'm encountering an issue where the position of the second menu is not aligned with the previous "Highlight" menu.

This is my implementation:

class ViewController: UIViewController {

    @IBOutlet weak var pdfView: PDFView!

    override func viewDidLoad() {
        super.viewDidLoad()

        pdfView.document = getDocument() 
        pdfView.usePageViewController(true)

        createMenu()
    }

    private func getDocument() -> PDFDocument? {
        guard let path = Bundle.main.path(forResource: "sample", ofType: "pdf") else {
            print("failed to get path.")
            return nil
        }
        let pdfURL = URL(fileURLWithPath: path)
        let document = PDFDocument(url: pdfURL)
        return document
    }

    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        if (action == #selector(highlight) || action == #selector(note)) {
            return true
        }
        return false
    }

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

    @objc private func highlight(_ sender: UIMenuController?) {
        guard let currentSelection = pdfView.currentSelection else { return }
        let selections = currentSelection.selectionsByLine()
        guard let page = selections.first?.pages.first else { return }

        selections.forEach { selection in
            let highlight = PDFAnnotation(bounds: selection.bounds(for: page), forType: .highlight, withProperties: nil)
            highlight.endLineStyle = .square
            page.addAnnotation(highlight)
        }

        let anotherItem = UIMenuItem(title: "Another", action: #selector(note(_:)))
        UIMenuController.shared.menuItems = [anotherItem]
        UIMenuController.shared.showMenu(from: self, rect: sender.menuFrame)
        UIMenuController.shared.setMenuVisible(true, animated: true)
    }

    @objc private func note(_ sender: UIMenuController) {

    }
}

Output:

enter image description here

0

There are 0 best solutions below