我已使用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)")
}
}
所以,如何仅删除所选的突出显示注释?
顺便说一句-我知道整个菜单项并不是真正相关,但是我希望有人在使用突出显示注释时能够找到这个问题,然后能够使用该部分。
谢谢,Emil。
在此观察此通知:PDFViewAnnotationHitNotification:https://developer.apple.com/documentation/foundation/nsnotification/name/1504809-pdfviewannotationhit
将目标添加到通知侦听器
当按下注释时,从userInfo中为“ PDFAnnotationHit”的PDFViewAnnotationHitNotification返回字典值,您将获得被按下的确切注释,一旦拥有该注释,则将其删除。