Skip to content

Instantly share code, notes, and snippets.

@derickito
Last active June 5, 2023 07:03
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save derickito/ac332db155ffbf0cff712d1680bd9fc0 to your computer and use it in GitHub Desktop.
Save derickito/ac332db155ffbf0cff712d1680bd9fc0 to your computer and use it in GitHub Desktop.
iOS PDFKit: How to add a highlight annotation
override func viewDidLoad() {
createMenu()
}
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)
}
pdfView.clearSelection()
}
@derickito
Copy link
Author

I can't take credit for this code. I found it on this Chinese website and thought there should be more examples like this one out on the web. https://qiita.com/ngo275/items/bbdc16daa58d2926b77c

@msuleman0100
Copy link

Thanks a lot for this piece of code buddy, it helped my like a life-saving-jacket 😄
Thanks for this contribution

@hameji
Copy link

hameji commented Jun 5, 2023

actually it is a japanese Page.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment