如何从pdf文件中删除注释

How to remove a annotation from a pdf file

我正在添加注释,但无法删除添加的注释。 例如:当我搜索 'Tubes' 单词时,它会标记每个 't' 字母。

示例图片:

我只想注释'tubes'个字

以及如何删除我添加的所有注释。 我该如何解决这些问题?

代码如下:

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)
         }
      }
   }
}

感谢大家的帮助:)

您可以定义一个函数来删除所有注释,如下所示,并在 searchBartextDidChange 方法中调用它:

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])
}