使用 PDFKit 删除突出显示注释

Emi*_*sen 0 pdf annotations highlight pdfkit swift

我使用 swift 和 PDFKit 成功地将突出显示注释添加到 pdf 中,但我无法弄清楚如何让用户再次删除突出显示。

用户可以正常选择文本,然后从 UIMenu 中选择“突出显示”或“删除突出显示”。

为了在选择文本时自定义 pdfView,我更改了显示的菜单 - 首先删除默认操作:

extension PDFView {
    override public func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        return false
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在 viewDidLoad() 中我设置了自定义 UIMenuItems:

let menuItem1 = UIMenuItem(title: "Highlight", action: #selector(highlightSelection(_:)))        
let menuItem2 = UIMenuItem(title: "Remove highlight", action: #selector(removeHighlightSelection(_:)))
UIMenuController.shared.menuItems = [menuItem1, menuItem2]
Run Code Online (Sandbox Code Playgroud)

选择突出显示时:

@objc func highlightSelection(_ sender: UIMenuItem) {
            let selections = pdfViewer.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.color = .yellow
                page.addAnnotation(highlight)
            })
    }
Run Code Online (Sandbox Code Playgroud)

到目前为止,一切都很好——到目前为止一切正常。文本被突出显示并创建注释。

现在我的问题来了:

当我选择突出显示的文本时,我希望用户能够通过点击“删除突出显示”来删除突出显示注释,但我根本不知道如何删除隐藏在所选文本“后面”的注释。

此代码有效,但删除了整个页面上的所有注释:

@objc func removeHighlightSelection(_ sender: UIMenuItem) {
        let selections = pdfViewer.currentSelection?.selectionsByLine()
        guard let page = selections?.first?.pages.first else { return }

        let annotationsToRemove = page.annotations

        for annotation in annotationsToRemove {
            page.removeAnnotation(annotation)
            print("Removed: \(annotation)")
        }
    }
Run Code Online (Sandbox Code Playgroud)

那么,如何仅删除选定的突出显示注释呢?

顺便说一句 - 我知道整个菜单的事情并不真正相关,但我希望有人在使用突出显示注释时会发现这个问题,然后能够使用该部分。

谢谢,埃米尔。

Pre*_*dea 5

观察此通知:此处的 PDFViewAnnotationHitNotification:https ://developer.apple.com/documentation/foundation/nsnotification/name/1504809-pdfviewannotationhit

将目标添加到通知监听器

当按下注释时,从“PDFAnnotationHit”的 PDFViewAnnotationHitNotification 的 userInfo 返回字典值,您将获得按下的确切注释,一旦获得此注释,请将其删除。