I am successfully adding a highlight annotation to a pdf using swift and PDFKit, but I am unable to figure out how to let the user remove the highlight again.
The user can select the text normally, and then choose "Highlight" or "Remove highlight" from the UIMenu.
To customise the pdfView when selecting text I have changed the menu that appears - first by removing the default actions:
extension PDFView {
override public func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
return false
}
}
Then in viewDidLoad() I've set my custom UIMenuItems:
let menuItem1 = UIMenuItem(title: "Highlight", action: #selector(highlightSelection(_:)))
let menuItem2 = UIMenuItem(title: "Remove highlight", action: #selector(removeHighlightSelection(_:)))
UIMenuController.shared.menuItems = [menuItem1, menuItem2]
When selecting highlight:
@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)
})
}
So far, so good - all working fine to this point. Text is highlighted and annotation created.
Now comes my issue:
When I select the highlighted text I want the user to be able to remove the highlight annotation by tapping "Remove highlight", but I simply cannot figure out how to remove just the annotation that hides "behind" the selected text.
This code is working, but removing all annotations on the entire page:
@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)")
}
}
So, how do I remove just the selected highlight annotation?
By the way - I know that the whole menu-thing is not really relevant, but I hope that somebody will find this question when working with highlight annotations and then be able to use that part.
Thanks, Emil.