Swift中使用PDFKit搜索PDF:findString参数实现求助
Hey there! I see you're getting started with PDFKit and trying to add string search functionality—great choice! Let's fix up that findString function and make it work properly.
First off, you might not know that PDFDocument already has a built-in findString(_:withOptions:) method that does exactly what you need. Your function can wrap this method to return the matching selections. Here's how to implement it correctly:
Step 1: Complete the findString Function
Update your function to use the PDF document from your pdfView, handle edge cases, and return the results:
// Make sure this is in the same class where your pdfView is declared func findString(_ string: String, withOptions options: NSString.CompareOptions = []) -> [PDFSelection] { // Guard against nil document first guard let document = pdfView.document else { print("No PDF document loaded!") return [] } // Use PDFDocument's built-in find method let selections = document.findString(string, withOptions: options) // Return the selections (could be empty if no matches found) return selections ?? [] }
Step 2: Understand the NSString.CompareOptions Parameter
The options let you customize how the search behaves. Here are some common ones you'll use:
.caseInsensitive: Ignore uppercase/lowercase differences (e.g., "Hello" matches "hello").wholeWord: Only match entire words (e.g., "cat" won't match "category").literal: Match the string exactly as written (no wildcard or regex behavior).diacriticInsensitive: Ignore accent marks (e.g., "café" matches "cafe")
You can combine multiple options using an array, like [.caseInsensitive, .wholeWord].
Step 3: How to Use the Function
Once your function is set up, you can call it from anywhere in your class. For example, to search for "Swift" with case-insensitive matching and jump to the first result:
// Example search call let searchResults = findString("Swift", withOptions: [.caseInsensitive]) if !searchResults.isEmpty { // Jump to the first matching selection in the PDFView pdfView.setCurrentSelection(searchResults[0], animate: true) // Optional: Loop through all results to do something else for selection in searchResults { print("Found match on page \(selection.page?.pageNumber ?? 0)") } } else { print("No matches found for the search string.") }
Quick Note on Your loadPDF Function
Your existing loadPDF looks good, just make sure pdfTitle is a valid string matching your PDF file name in the bundle. If you ever need to reload the PDF, this function will work perfectly.
内容的提问来源于stack exchange,提问作者mrwadepro

