我使用 swift 和 PDFKit 成功向 pdf 添加突出显示注释,但我无法弄清楚如何让用户再次删除突出显示。
用户可以正常选择文本,然后从 UIMenu 中选择“突出显示”或“删除突出显示”。
为了在选择文本时自定义 pdfView,我更改了显示的菜单 - 首先删除默认操作:
extension PDFView {
override public func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
return false
}
}
然后在 viewDidLoad() 中我设置了自定义 UIMenuItems:
let menuItem1 = UIMenuItem(title: "Highlight", action: #selector(highlightSelection(_:)))
let menuItem2 = UIMenuItem(title: "Remove highlight", action: #selector(removeHighlightSelection(_:)))
UIMenuController.shared.menuItems = [menuItem1, menuItem2]
选择突出显示时:
@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)
})
}
到目前为止,一切顺利 - 到目前为止一切正常。文本突出显示并创建注释。
现在是我的问题:
当我选择突出显示的文本时,我希望用户能够通过点击“删除突出显示”来删除突出显示注释,但我根本不知道如何删除隐藏在所选文本“后面”的注释。
此代码有效,但删除了整个页面上的所有注释:
@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)")
}
}
那么,如何仅删除选定的突出显示注释?
顺便说一句 - 我知道整个菜单内容并不真正相关,但我希望有人在使用突出显示注释时会发现这个问题,然后能够使用该部分。
谢谢, 埃米尔。
最佳答案
观察此通知:PDFViewAnnotationHitNotification 此处:https://developer.apple.com/documentation/foundation/nsnotification/name/1504809-pdfviewannotationhit
将目标添加到通知监听器
当按下注释时,从“PDFAnnotationHit”的 PDFViewAnnotationHitNotification 的 userInfo 返回字典值,您将获得按下的确切注释,一旦获得此注释,请将其删除。
关于swift - 使用 PDFKit 删除突出显示注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58616468/