How Do I Customize the Search Results from SearchViewController?
To customize the search results from SearchViewController
, you need to subclass SearchViewController
and override TextSearchDelegate.didFinish(_:term:searchResults:isFullSearch:pageTextFound:)
:
class CustomSearchViewController: SearchViewController { override func didFinish(_ textSearch: TextSearch, term searchTerm: String, searchResults: [SearchResult], isFullSearch: Bool, pageTextFound: Bool) { // Filter out the matching search results that are not at the beginning of the word. var filteredSearchResults = [SearchResult]() searchResults.forEach { searchResult in let words = searchResult.previewText.components(separatedBy: .punctuationCharacters) words.forEach { word in if word.lowercased().hasPrefix(searchTerm.lowercased()) { filteredSearchResults.append(searchResult) } } } super.didFinish(textSearch, term: searchTerm, searchResults: filteredSearchResults, isFullSearch: isFullSearch, pageTextFound: pageTextFound) } }
@interface CustomSearchViewController : PSPDFSearchViewController @end @implementation CustomSearchViewController - (void)didFinishSearch:(PSPDFTextSearch *)textSearch term:(NSString *)searchTerm searchResults:(NSArray<PSPDFSearchResult *> *)searchResults isFullSearch:(BOOL)isFullSearch pageTextFound:(BOOL)pageTextFound { // Filter out the matching search results that are not at the beginning of the word. NSMutableArray<PSPDFSearchResult *> *filteredSearchResults = [NSMutableArray new]; [searchResults enumerateObjectsUsingBlock:^(PSPDFSearchResult * _Nonnull searchResult, NSUInteger idx, BOOL * _Nonnull stop) { NSArray <NSString *> *words = [searchResult.previewText componentsSeparatedByCharactersInSet:[NSCharacterSet punctuationCharacterSet]]; for (NSString *word in words) { if ([word.lowercaseString hasPrefix:searchTerm.lowercaseString]) { [filteredSearchResults addObject:searchResult]; } } }]; // Call super with the new filtered search results. [super didFinishSearch:textSearch term:searchTerm searchResults:filteredSearchResults isFullSearch:isFullSearch pageTextFound:pageTextFound]; } @end