0

I'm adding an annotation but I can't remove my added annotation. For Example: When I search 'Tubes' word it marks every 't' letter.

Example Image:

I only want to annotate 'tubes' word.

And how can I remove all of the annotations I added. How can I solve these problems?

Here is the code:

var pdfView: PDFView!

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    return highlight(searchTerms: [searchText])
}

public func highlight(searchTerms: [String]?)
{
    var highlight = PDFAnnotation()
   searchTerms?.forEach { term in
    let selections = pdfView?.document?.findString(term, withOptions: [.forcedOrdering])
      selections?.forEach { selection in
         selection.pages.forEach { page in
            highlight = PDFAnnotation(bounds: selection.bounds(for: page), forType: .highlight, withProperties: nil)
            highlight.endLineStyle = .square
            highlight.color = UIColor.yellow.withAlphaComponent(0.5)
            page.addAnnotation(highlight)
         }
      }
   }
}

Thanks for all help :)

Mahmut Acar
  • 713
  • 2
  • 7
  • 26
caneraltuner
  • 263
  • 1
  • 3
  • 12

1 Answers1

3

You can define a function for remove all annotations like below and call it in searchBar's textDidChange method:

func removeAllAnnotations() {
    guard let document = pdfView.document else { return }

    for index in 0..<document.pageCount {
        if let page = document.page(at: index) {
            let annotations = page.annotations
            for annotation in annotations {
                page.removeAnnotation(annotation)
            }
        }
    }
}

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    removeAllAnnotations()
    return highlight(searchTerms: [searchText])
}

Mahmut Acar
  • 713
  • 2
  • 7
  • 26