Khorwin
Khorwin

Reputation: 445

How to highlight search results in PDFKit - iOS

I use PDFKit for iOS 11, using search functions, i got some PDFSelection elements. How to highlight the text corresponding to this selection in the PDF?

I tried with this, but isn't working :

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

Upvotes: 2

Views: 1801

Answers (2)

Justeen
Justeen

Reputation: 11

Assuming you're grabbing the highlighted text from a UISearchBar, here's a solution I came up with for 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)
            }
            
        })    
    }

Upvotes: 0

Rafał Rębacz
Rafał Rębacz

Reputation: 495

You forgot to add selection to the PDFView:

@IBOutlet weak var pdfView: PDFView!

pdfView.setCurrentSelection(selection, animate: true)

Also it looks like selection.draw is not necessary step.

Upvotes: 5

Related Questions