如何在 PDFKit 中突出显示搜索结果 - iOS.



我在iOS 11中使用PDFKit,使用搜索功能,我得到了一些PDFSelection元素。如何在PDF中突出显示与此选择相对应的文本?

我尝试过这个,但不起作用:

selection.color = UIColor.red
selection.draw(for: selection.pages.first!, active: true)

您忘了在 PDFView 中添加选择:

@IBOutlet weak var pdfView: PDFView!
pdfView.setCurrentSelection(selection, animate: true)

而且看起来selection.draw不是必要的步骤。

假设您正在从 UISearchBar 中抓取突出显示的文本,以下是我为 Swift 5 提出的解决方案:

    func searchBarSearchButtonClicked(_ seachBar: UISearchBar) {
        let searchText = searchBar.text ?? ""
        let selectionList = pdfView.document?.findString(searchText, withOptions: NSString.CompareOptions.caseInsensitive)
        
        guard let page = selectionList?.first?.pages.first else { return }
        selectionList?.forEach({ selection in
            selection.pages.forEach { page in
                let highlight = PDFAnnotation(bounds: selection.bounds(for: page), forType: .highlight, withProperties: nil)
                    highlight.endLineStyle = .square
                    highlight.color = UIColor.orange.withAlphaComponent(0.5)
                    page.addAnnotation(highlight)
            }
            
        })    
    }